Consider the following code:
#include <stdio.h>
class A
{
public:
friend void foo(A a){ printf("3\n"); }
};
int main()
{
foo(A());
}
It works. But I thought that this code is invalid. It is because 3.4.1/3:
For purposes of determining (during parsing) whether an expression is
a postfix-expression for a function call, the usual name lookup rules
apply.
Usual name lookup rules could not find the friend function because name declared by friend is invisible in the global namespace in my case. Actually 3.3.1/4:
friend declarations (11.3) may introduce a (possibly not visible) name
into an enclosing namespace
This implies that the programm is ill-formed. It is because that there is no name which found during the determining is the expression foo(A()); is a postfix-expression for a function call.
I'm confusing...
When parsing the following program
#include <iostream>
using namespace std;
typedef int foo;
class A
{
public:
operator int(){
return 42;
}
};
int main()
{
cout << foo(A());
}
the output will be 42 because 3.4.1/3
For purposes of determining (during parsing) whether an expression is
a postfix-expression for a function call, the usual name lookup rules
apply.
that means: to determine if foo is a postfix-expression (e.g. a cast) or a function call, the compiler will first use name lookup and search for it in the global namespace and/or enclosing scopes / base classes (or with fully qualified lookups if available).
Now take this code:
#include <iostream>
using namespace std;
class A
{
public:
friend int foo(A a){ return 55; }
operator int(){
return 42;
}
};
int main()
{
cout << foo(A());
}
The above will output 55 thanks to ADL: foo will be found by searching inside the scopes defined by its potential arguments, i.e. A.
A friend declaration introduces a (possibly not visible) name as you posted (3.3.1/4)
friend declarations (11.3) may introduce a (possibly not visible) name
into an enclosing namespace
that means the following code will not work
#include <iostream>
using namespace std;
class A
{
public:
friend int foo(A a){ return 55; }
operator int(){
return 42;
}
};
int main()
{
cout << ::foo(A()); // Not found
cout << A::foo(A()); // Not found
}
You might want to search for "friend name injection" and/or the Barton-Nackman trick.
Short story: now ordinary lookups can't find friend declarations.
So the code you posted is well-formed because ADL allows it to run as I explained in the previous passages.
Related
In Chapter 7 of "Inside the C++ Object Model," it was written that the resolution of a nomember name depends on whether the use of name is related to "the type of parameter used to instantiate the template."
I write a test:
/// -------------Test.h---------------
#ifndef TEST_H
#define TEST_H
#include <iostream>
using namespace std;
extern double foo(double t);
template <typename T>
class Test {
public:
void fun1() {
member = foo(val);
}
T fun2() {
return foo(member);
}
private:
int val;
T member;
};
#endif
and
/// -------------test1.cc-------------
#include <iostream>
using namespace std;
double foo(double t) {
cout << "foo doule is called" << endl;
return t;
}
int foo(int t) {
cout << "foo int is called" << endl;
return t;
}
-------------test.cc--------------
#include "Test.h"
extern int foo(int t);
int main() {
Test<int> fi;
fi.fun1();
fi.fun2();
return 0;
}
I expect "foo double is called\n
foo int is called",
but I got "foo double is called\n
foo double is called".
My g++ version is bellow. I'll be appreciate it if you can help me.
I'm afraid the book is not painting the complete picture (and it's a bit aged). Yes, foo(member) is a function call that is dependent on the template parameter. But the specific way in which functions are looked up in templates is described in the C++ standard at [temp.dep.candidate]:
For a function call where the postfix-expression is a dependent name,
the candidate functions are found using the usual lookup rules
([basic.lookup.unqual], [basic.lookup.argdep]) except that:
For the part of the lookup using unqualified name lookup, only function declarations from the template definition context are found.
For the part of the lookup using associated namespaces ([basic.lookup.argdep]), only function declarations found in either
the template definition context or the template instantiation context
are found.
foo's overloads can be looked up in one of two ways. By direct unqualified lookup, and by argument dependent lookup (aka ADL). Simple unqualified lookup considers only the names that are known at the point of the template definition. Since you only declared foo(double), that is the only overload found at the point of the template definition.
At the point of instantiation, the compiler will try to do ADL to find more foo's, but fundamental types don't contribute to ADL. int cannot be used to find foo(int). So the compiler can do only one thing, convert the integer to a double, and call foo(double).
If you want to test your compilers ADL, you just need to add a simple user defined type and overload. For instance:
enum E{};
E foo(E) {
cout << "foo E is called\n";
return {};
}
int main() {
Test<E> fi;
fi.fun1();
fi.fun2();
return 0;
}
I just noticed this. I don't know why this is the case, if i use one element from a namespace i don't want anything else to be accessible without having to use the namespace. For example here, this code is valid:
namespace Test
{
struct Magic
{
int poof;
};
struct Magic2
{
int poof;
};
int Alakazam(const Magic& m)
{
return m.poof;
}
int Alakazam(const Magic2& m)
{
return m.poof;
}
};
using Magic = Test::Magic;
int main()
{
Alakazam(Magic()); // valid
Alakazam(Test::Magic2()); // valid
Test::Alakazam(Magic()); // what i want to only be valid
Test::Alakazam(Test::Magic2()); // this too
}
Any reasoning behind this? Does the spec state that this has to be true?
As suggested by immbis in the comment, this is defined by the standard:
3.4.2: Argument dependent name lookup
When the postfix-expression in a function call is an unqualified-id, other namespaces not considered during the usual
unqualified lookup may be searched, and in those namespaces,
namespace-scope friend function or function template declarations not
otherwise visible may be found. These modifications to the search
depend on the types of the arguments (and for template template
arguments, the namespace of the template argument).
...
If you want to defeat this mecanism, you have to use nested namespace like this, but it's tricky:
namespace Test
{
struct Magic
{
int poof;
};
struct Magic2
{
int poof;
};
namespace Test2 { // use a nested namespace that will not be searched autoamtically
int Alakazam(const Magic& m)
{
return m.poof;
}
int Alakazam(const Magic2& m)
{
return m.poof;
}
}
using namespace Test2; // but give some access to the enclosing namespace
};
Live Demo : Then, your two first calls will not be valid any longer. However, the last call in your example is still possible: you can't prevent the use of fully qualified names outside of the namespace.
Consider the code:
template<typename T>
class Foo{};
namespace X
{
class X{};
}
using namespace X; // now both class X and namespace X are visible
Foo<X::X> f()
{
return {};
}
int main() {}
gcc5.2 compiles the code with no errors whatsoever. However clang spits the error:
error: 'X' is not a class, namespace, or enumeration
Foo f()
error: reference to 'X' is ambiguous
Is the code syntactically valid, according to the C++ standard? Or is just a gcc bug? Removing the qualified name X::X and using Foo<X> instead makes gcc choke also
error: template argument 1 is invalid
Foo f()
[namespace.udir]/6:
If name lookup finds a declaration for a name in two different
namespaces, and the declarations do not declare the same entity and do
not declare functions, the use of the name is ill-formed.
For the first X in X::X, both the namespace and the class are considered. However, the name of the namespace resides in the global namespace while the class resides in namespace X; Hence the above quote applies, Clang is therefore correct. (This also occurs when just writing X, clearly).
::X removes this ambiguity. Lookup does not proceed into the namespace anymore. [namespace.qual]/2:
For a namespace X and name m, the namespace-qualified lookup set
S(X, m) is defined as follows: Let
S0(X, m) be the set of all declarations of m in X and the inline namespace set of X (7.3.1). If S0(X, m) is
not empty, S(X, m) is S0(X, m); otherwise, […]
Here, X is the global namespace and m is "X". Clearly, the declaration of our namespace is found, so lookup is definite here.
Not a complete answer but that is a clear situation that shows even declaring using namespace, for objects with the same name as the namespace you need to declare the namespace.
#include <iostream>
#include <string>
namespace test
{
void function1(void){std::cout << "Function inside the namespace" << std::endl;}
class test
{
public:
static void function1(void){std::cout << "Function inside the class" << std::endl;}
};
};
using namespace test;
int main()
{
function1();
test::function1();
test::test::function1();
}
Output (GCC 4.9.2)
"Function inside the namespace"
"Function inside the namespace"
"Function inside the class"
For practice, I wrote some template functions whose names are the same as the stl algorithms. But my code can not compile
error: Call to < algorithm_name > is ambiguous.
I only included using std::necessary_names; in my code rather than using namespace std;.
Usually when you have using, the "used" name takes precedence:
namespace N { int x = 0; }
int x = 1;
int main() {
using N::x;
cout << x;
}
// Output: 0
However, Argument-Dependent Lookup can mess this up:
namespace N {
struct T {};
void f(T) {}
}
namespace M {
void f(N::T) {}
}
int main() {
using M::f;
N::T o;
f(o); // <--- error: call of overloaded 'f(N::T&)' is ambiguous
}
So, if you are having trouble, qualify your own namespace (in this example, M) explicitly:
namespace N {
struct T {};
void f(T) { cout << "N::f"; }
}
namespace M {
void f(N::T) { cout << "M::f"; }
}
int main() {
using M::f;
N::T o;
M::f(o); // <--- Output: "M::f"
}
In a somewhat bizarre twist, you can also use parentheses to prevent ADL:
namespace N {
struct T {};
void f(T) { cout << "N::f"; }
}
namespace M {
void f(N::T) { cout << "M::f"; }
}
int main() {
using M::f;
N::T o;
(f)(o); // <--- Output: "M::f"
}
Explanation
[n3290: 3.4.1/1]: [re: unqualified name lookup] In all the cases
listed in 3.4.1, the scopes are searched for a declaration in the
order listed in each of the respective categories; name lookup ends
as soon as a declaration is found for the name. If no declaration is
found, the program is ill-formed.
[n3290: 3.4.1/2]: [i.e. first priority] The declarations from the
namespace nominated by a using-directive become visible in a namespace
enclosing the using-directive; see 7.3.4. For the purpose of the
unqualified name lookup rules described in 3.4.1, the declarations
from the namespace nominated by the using-directive are considered
members of that enclosing namespace.
[n3290: 3.4.2/1]: [re: argument-dependent lookup] When the postfix-expression in a function call
(5.2.2) is an unqualified-id, other namespaces not considered during
the usual unqualified lookup (3.4.1) may be searched, and in those
namespaces, namespace-scope friend function declarations (11.3) not
otherwise visible may be found. These modifications to the search
depend on the types of the arguments (and for template template
arguments, the namespace of the template argument).
i.e. Normal lookup stops at the name that you brought into scope with using, but when ADL comes into play, other names are also added to the candidate set, causing an ambiguity between two names.
It's better to declare your own version in a namespace; so that such problem would not occur.
namespace MySTL
{
template<typename T, ... > // ... means other template params
class vector;
template<typename T, ... >
class queue;
...
}
now you can do,
using std::vector;
which will not collide with MySTL::vector.
Chances are that you are hitting a problem with Argument Dependent Lookup. When you pass a type that is defined within a namespace to an unqualified function, the namespaces of all the arguments are implicitly added to the lookup set, and that might cause collisions. You can try to qualify your own algorithm calls to inhibit ADL from kicking in.
namespace n {
struct test {};
void foo( test const & ) {}
};
int main() {
n::test t;
foo( t ); // Will find n::foo as the argument belongs to n namespace
}
A point from the ISO C++ draft (n3290): 3.4.3.2/1 Namespace members
If the nested-name-specifier of a qualified-id nominates a namespace,
the name specified after the nested-name-specifier is looked up in
the scope of the namespace. If a qualified-id starts with ::, the
name after the :: is looked up in the global namespace. In either
case, the names in a template-argument of a template-id are looked up
in the context in which the entire postfix-expression occurs.
Here can any one explain about the BOLD part .... and from earlier c++03 draft to c++0x draft he added
If a qualified-id starts with ::, the name after the :: is looked up
in the global namespace.
can any one explain with an example program please
::S is a qualified-id.
In the qualified-id ::S::f, S:: is a nested-name-specifier.
In informal terms, a nested-name-specifier is the part of the id that
begins either at the very beginning of a qualified-id or after the initial scope resolution operator (::) if one appears at the very beginning of the id and
ends with the last scope resolution operator in the qualified-id.
Very informally, an id is either a qualified-id or an unqualified-id. If the id is a qualified-id, it is actually composed of two parts: a nested-name specifier followed by an unqualified-id.
Given:
struct A {
struct B {
void F();
};
};
A is an unqualified-id.
::A is a qualified-id but has no nested-name-specifier.
A::B is a qualified-id and A:: is a nested-name-specifier.
::A::B is a qualified-id and A:: is a nested-name-specifier.
A::B::F is a qualified-id and both B:: and A::B:: are nested-name-specifiers.
::A::B::F is a qualified-id and both B:: and A::B:: are nested-name-specifiers.
Another example:
#include <iostream>
using namespace std;
int count(0); // Used for iteration
class outer {
public:
static int count; // counts the number of outer classes
class inner {
public:
static int count; // counts the number of inner classes
};
};
int outer::count(42); // assume there are 42 outer classes
int outer::inner::count(32768); // assume there are 2^15 inner classes
// getting the hang of it?
int main() {
// how do we access these numbers?
//
// using "count = ?" is quite ambiguous since we don't explicitly know which
// count we are referring to.
//
// Nested name specifiers help us out here
cout << ::count << endl; // The iterator value
cout << outer::count << endl; // the number of outer classes instantiated
cout << outer::inner::count << endl; // the number of inner classes instantiated
return 0;
}
EDIT:
In response to your comment, I believe that statement simply means that the arguments of a template are handled w.r.t the context and line by which they are declared. For example,
in f.~foo();, foo is looked up within f., and within the scope of foo<int>, it is valid to refer to it just with with foo.
It is called as Qualified name lookup.
The leading :: refers the global namespace. Any qualified identifier starting with a :: will always refer to some identifier in the global namespace over the same named identifier in local namespace.
namespace A
{
namespace B
{
void doSomething();
}
}
namespace Z
{
namespace A
{
namespace B
{
void doSomething();
}
}
using namespace A::B // no leading :: refers to local namespace layer
void doSomethingMore()
{
doSomething(); // calls Z::A::B::doSomething();
}
}
namespace Z
{
namespace A
{
namespace B
{
void doSomething();
}
}
using namespace ::A::B // leading :: refers to global namespace A
void doSomethingMore()
{
doSomething(); // calls ::A::B::doSomething();
}
}
The bolded text refers to two different situations. The first part is the distinction of using or not using :: as a prefix. When a qualified name starts with :: the exact namespace is checked starting from the empty namespace, while if it is not present, the search will consider nested namespaces:
namespace A {
void f() { std::cout << "::A::f" << std::endl; }
}
namespace B {
namespace A {
void f() { std::cout << "::B::A::f" << std::endl; }
}
void g() {
A::f(); // ::B::A::f
::A::f(); // ::A::f
}
}
The last sentence in the paragraph refers to the specific of template arguments, and it tells you that the lookup will not start in the namespace that the template was declared, but rather in the namespace where it is being instantiated:
struct A {
static void f() { std::cout << "::A::f()" << std::endl; }
};
template <typename T>
void f() {
T::f();
}
namespace N {
struct A {
static void f() { std::cout << "::N::A::f()" << std::endl; }
};
void g() {
f<A>();
}
}
If lookup started in the template namespace, the call f<A>() would refer to f<::A>, but that clause in the standard states the lookup will start inside namespace N (where the entire postfix-expression occurs), and will thus call ::N::A::f().
int a(1);
class someCls {
private:
int a;
public:
// Assigns this->a with the value of the global variable ::a.
void assignFromGlobal() {
a = ::a;
}
};