Overload not considered even though it looks like a better match - c++

This is rejected by both gcc (live on godbolt) and clang:
#include <string>
namespace
{
std::string
to_string(char const (&str) [14])
{ return str; }
}
void f()
{
using std::to_string;
char const hello[14] = "Hello, World!";
(void) to_string(hello);
}
The compiler considers each of the std::to_string overloads and conclude with:
error: no matching function for call to 'to_string(const char [14])'
If I remove using std::to_string, my overload is considered and called. Why? How to fix it (other than removing the using)?

The scope of the using declaration matters. It's a proper declaration, so name hiding takes effect. Inside the function the global scope version isn't visible. You need to reintroduce it:
using ::to_string;
using std::to_string;

This using declaration
using std::to_string;
hides the declaration in the global namespace. So the compiler does not see the function ::to_string.
So you have to write
using std::to_string;
using ::to_string;
And make the unnamed namespace inline.
inline namespace
{
// ...
}

Related

Using fully qualified name for std namespace in C++

If name in C++ is not fully qualified, e.g. std::cout, it can lead to an unintentional error, such as mentioned at https://en.cppreference.com/w/cpp/language/qualified_lookup. But using a fully qualified name for ::std namespace, e.q. ::std::cout, is very rare, as I have noticed.
Is there any reason why a fully qualified name for ::std namespace is not used?
And what about using fully qualified name for own created namespaces? Is it good idea?
You are completely right, in the sense that yyyy::xxx can be ambiguous if there is a namespace yyyy and also a class yyyy which are both visible in the same scope. In this case only the full qualification ::yyyy::xxx can solve the ambiguity. The example of your link makes it very clear:
// from cppreference.com
#include <iostream>
int main() {
struct std{};
std::cout << "fail\n"; // Error: unqualified lookup for 'std' finds the struct
::std::cout << "ok\n"; // OK: ::std finds the namespace std
}
But in practice, it's difficult to create a conflicting std at top level, since most of the includes from the standard library will make it fail:
#include <iostream>
struct std { // OUCH: error: ‘struct std’ redeclared as different kind of symbol
int hello;
};
This means that to create a conflict, you'd need to define local classes or introduce a using clause in another namespace. In addition, nobody will (dare to) call a class std.
Finally, in practice, ::yyyy::xxx is less convenient to read. All this explains why you won't find it very often.
Additional remark
The problem is not so much for std which is well known, but rather for your own namespaces and third party libraries. In this case, the namespace alias would be a better alternative to :::yyyy to disambiguate:
namespace foo {
void printf() { }
}
int main() {
foo::printf(); // ok, namespace is chose because no ambiguity
struct foo {/*...*/ }; // creates ambiguity
//foo::printf(); // error because struct foo is chosen by name lookup
::foo::printf(); // ok, but not if you decide to move the code to be nested in another namespace
namespace mylib = foo ; // or ::foo (see discussion below)
mylib::printf(); // full flexibility :-)
}
Its advantage is a higher flexibility. Suppose for example that you'd move your code to nest it in an enclosing namespace. With the namespace alias, your code could continue to work as is (in the worst case with a minor adjustment in the alias definition). With the global scope resolution, you'd have to change all the statements where the global namespace ::foo would be used.
To maintain big code or better readability or clashes in names, C++ has provided namespace " a declarative region".
A namespace definition can appear only at global scope, or nested within another namespace.
#Sample Code
#include <iostream>
int main()
{
struct std{};
std::cout << "fail\n"; // Error: unqualified lookup for 'std' finds the struct
::std::cout << "ok\n"; // OK: ::std finds the namespace std
}
In the above code compiler is looking for cout in struct std , but in next line when you use ::std::cout it looks for cout in globally defined std class.
Solution:
#include <iostream>
//using namespace std; // using keyword allows you to import an entire namespace at once.
namespace test
{
void cout(std::string str)
{
::std::cout<<str;
}
}
int main()
{
cout("Hello");//'cout' was not declared in this scope
::test::cout("Helloo ") ;
::std::cout<<"it is also ok\n";
}
Or use the in this way , it is just for better readability
##
using namespace test;
int main()
{
cout("Hello");//'cout' was not declared in this scope
cout("Helloo ") ;
::std::cout<<"it is also ok\n";
}

How can I call a namespace inside a function?

Something interesting and wrong about my code.
#include <iostream>
void func(){
using namespace std;
}
main(){
func(); //Here the function will introduce the (using namespace std declaration) in the code
cout << "Hello World!";
return (0);
}
When compiled the error message is shown:
atizva#atizva:~/Documents/C++/Programs$ g++ -o func function_call.cpp
function_call.cpp: In function ‘int main()’:
function_call.cpp:7:2: error: ‘cout’ was not declared in this scope
cout << "Hello World!";
^~~~
function_call.cpp:7:2: note: suggested alternative:
In file included from function_call.cpp:1:0:
/usr/include/c++/7/iostream:61:18: note: ‘std::cout’
extern ostream cout; /// Linked to standard output
^~~~
I don't understand why the function 'func()' doesn't call the tag: 'using namespace std' appropriately.
To fix this, you would have to move using namespace std; outside of func(). The reason this fails in your current code is that using declaration only applies within the scope that it is called (in this case func()). So once you exit func(), you lose the effects of using namespace std;
You assume that namespaces are enabled at runtime, but namespaces are only meaningful at compile time. What you are doing is to limit the use of std to the scope of the function func(). That is, it allows you to type
cout
inside that function, but not elsewhere.

Overloading a function defined in a namespace

Why is the following code illegal?
#include <iostream>
using namespace std;
namespace what {
void print(int count) {
cout << count << endl;
}
}
void what::print(const string& str) {
cout << str << endl;
}
int main() {
what::print(1);
what::print("aa");
return 0;
}
The error I get when compiling with clang and -std=c++14 is
error: out-of-line definition of 'print' does not match any declaration in namespace 'what'
I know the fix to the problem but I am wondering why the compiler thinks that I am trying to define the function (print) instead of overload it.
The reason it is not working for you is because the syntax
void what::print(const string& str)
is basically saying
inside the what namespace, define the print function here
If you want to define a function outside of its namespace, you must declare it in the namespace beforehand.
§13.1 of the standard states, "When two or more different declarations are specified for a single name in the same scope, that name is said
to be overloaded."
Overloads of a function must be in the same scope of each other. It is just how the language works.

Is it ok to wrap code in anonymous namespaces for using directives? [duplicate]

This question already has answers here:
Is using namespace in an anonymous namespace safe?
(2 answers)
Closed 3 months ago.
I want using namespace std; to apply to classes as well as functions without polluting the global namespace, but I'm wondering if it's an ok approach.
namespace
{
using namespace std;
class S
{
public:
S()
{
cout << "ok";
}
friend ostream operator<<(ostream& os, const S& s);
};
}
Any caveats to this?
It will work but keep in mind the following points:
You should limit its use in a source file, not in a header file (in general you should refrain from using unnamed namespaces in headers since they can easily mess around with your symbol definitions, especially if there are inline functions that use something from the anonymous namespace).
It's a bad practice and adding an additional naming hierarchy layer (i.e. the anonymous namespace) just for laziness is as bad as it sounds.
If it's in header file then it's not preferable as this file could be included in multiple source file. If in some source file then its acceptable
Whilst this looked like a great solution, in my experiments it doesn't do as I expected it would. It doesn't limit the scope of the using directive.
Consider this:
#include <string>
namespace {
string s1; // compile error
}
namespace {
string s2; // compile error
}
string s3; // compile error
int main()
{
}
None of those strings compile because they are not properly qualified. This is what we expect.
Then consider this:
#include <string>
namespace {
using namespace std;
string s1; // compiles fine (as expected)
}
namespace {
string t2; // compiles fine (I didn't expect that)
}
string v3; // compiles fine (I didn't expect that either)
int main()
{
}
So placing a using directive within an unnamed namespace appears to be exactly the same as placing it in the global namespace.
EDIT: Actually, placing a symbol in an unnamed namespace makes it local to the translation unit. So this is why it can't work for the intended purpose.
Therefore it has to be a no-no for headers.
An unnamed namespace doesn't contain the effects of a using-directive:
namespace A {int i;}
namespace {
using namespace A;
}
int j=i,k=::i; // OK
Both qualified and unqualified lookup follow the implicit using-directive for the unnamed namespace and then follow the explicit one within it. Wrapping the unnamed namespace inside another namespace limits the unqualified case to other code within that outer namespace, of course:
namespace A {int i;}
namespace B {
namespace {
using namespace A;
}
int j=i; // OK, as above
}
int j=i, // error: i not found
k=B::i; // OK
However, in either case you might as well write the using-directive outside the unnamed namespace (or not write it at all if it would be problematic, perhaps because it would appear in a header file).
Don't take the decision to use an anonymous namespace just so you can limit the scope of a using directive.
That being said, if an anonymous (or any other) namespace is already there and you want the advantages of the using inside it, it's fine as long as your coding standards okay it.

What is the need to specify "std" prefix?

I'm a beginner in programming and I often see many programs using the prefix std if they are using any std functions like std::cout, std::cin, etc. I was wondering what is it's purpose ? Is it just a way of good programming or is there more to it ? Does it make any difference for the compiler or is it readability or what ? Thanks.
The STL types and functions are defined in the namespace named std. The std:: prefix is used to use the types without fully including the std namespace.
Option 1 (use the prefix)
#include <iostream>
void Example() {
std::cout << "Hello World" << std::endl;
}
Option #2 (use the namespace)
#include <iostream>
using namespace std;
void Example() {
cout << "Hello World" << endl;
}
Option #3 (use types individually)
#include <iostream>
using std::cout;
using std::endl;
void Example() {
cout << "Hello World" << endl;
}
Note: There are other implications to including an entire C++ namespace (option #2) other than not having to prefix every type / method with std:: (especially if done within a header) file. Many C++ programmers avoid this practice and prefer #1 or #3.
C++ has a concept of namespaces.
namespace foo {
int bar();
}
namespace baz {
int bar();
}
These two functions can coexist without conflict, since they're in different namespaces.
Most of the standard library functions and classes live in the "std" namespace. To access e.g. cout, you need to do one of the following, in order of preference:
std::cout << 1;
using std::cout; cout << 1;
using namespace std; cout << 1;
The reason you should avoid using is demonstrated with the above foo and baz namespaces. If you had using namespace foo; using namespace baz; any attempt to call bar() would be ambiguous. Using the namespace prefix is explicit and exact, and a good habit.
Nobody mentioned in their answer that a using namespace foo statement can be put inside a function body, thereby reducing namespace contamination in other scopes.
For example:
// This scope not affected by using namespace statement below.
void printRecord(...)
{
using namespace std;
// Frequent use of std::cout, io manipulators, etc...
// Constantly prefixing with std:: would be tedious here.
}
class Foo
{
// This scope not affected by using namespace statement above.
};
int main()
{
// This scope not affected either.
}
You can even put a using namespace foo statement inside a local scope (pair of curly braces).
It's a C++ feature called namespaces:
namespace foo {
void a();
}
// ...
foo::a();
// or:
using namespace foo;
a(); // only works if there is only one definition of `a` in both `foo` and global scope!
The advantage is, that there may be multiple functions named a - as long as they are within different namespaces, they can be used unambiguously (i.e. foo::a(), another_namespace::a()). The whole C++ standard library resides in std for this purpose.
Use using namespace std; to avoid the prefix if you can stand the disadvantages (name clashes, less clear where a function belongs to, ...).
It's short for the standard namespace.
You could use:
using namespace std
if you don't want to keep using std::cout and just use cout