gccnamespacesc++14using-directivesreturn-type-deduction

Problems after commenting out "using namespace std;"


I'm new to C++ and I read that "using namespace std;" is considered bad practice. I used the following code to test if my compiler was c++14 compliant:

#include <iostream>
#include <string>
using namespace std;
auto add([](auto a, auto b){ return a+b ;});
auto main() -> int {cout << add("We have C","++14!"s);}

No errors. Then I started to play around with the code – as you do... when you learn something new. So I commented out using namespace std; and replaced cout with std::cout. Now the code looked like this:

#include <iostream>
#include <string>
//using namespace std;
auto add([](auto a, auto b){ return a+b ;});
auto main() -> int {std::cout << add("We have C","++14!"s);}

Build Messages:

||=== Build: Release in c++14-64 (compiler: GNU GCC Compiler) ===|
C:\CBProjects\c++14-64\c++14-64-test.cpp||In function 'int main()':|
C:\CBProjects\c++14-64\c++14-64-test.cpp|5|error: unable to find string literal operator 'operator""s' with 'const char [6]', 'long long unsigned int' arguments|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Questions:


Solution

  • clang++ gives a good error message:

    error: no matching literal operator for call to 'operator""s' with arguments of types 'const char *' and 'unsigned long', and no matching literal operator template
    auto main() -> int { std::cout << add("We have C", "++14!"s); }
                                                              ^
    

    You use string literals and more precisely operator""s.

    By removing using namespace std; you have to specify the namespace where the operator is defined.

    With an explicit call:

    int main() {
      std::cout << add("We have C", std::operator""s("++14!", 5));
      // Note the length of the raw character array literal is required
    }
    

    or with a using declaration:

    int main() {
      using std::operator""s;
      std::cout << add("We have C", "++14!"s);
    }