Question about folding links in C ++ 0x

I do not know why this code cannot be compiled. I'v tested in Visual C ++ 2010 and gcc with -std = C ++ 0x. Does anyone give any suggestion? thanks!

template<typename T> class Foo { public: void test(const T&){cout<<"const";} void test( T&){cout<<"non const";} }; int main() { int a; Foo<int&> f; } 

compilation error: 'void Foo :: test (T)': member function already defined or declared

but why can this be compiled?

 template<typename T> void foo(const T&){cout<<"const"; } template<typename T> void foo( T&){cout<<"non const"; } int main() { int a; foo<int&>(a); } 

i'v read C ++ 0x article said: T & and == T &, therefore const T & and == const T &

+5
source share
3 answers

i'v read C ++ 0x article said: T & and == T &, therefore const T & and == const T &

Actually, this does not make much sense. IMHO, it is better to put this in a table:

 T T& const T const T& --------------------------------------- int int& const int const int& int& int& int& int& (1) (2) (1+2) 1: Reference collapsing in action 2: const applies to the reference and is therefore ignored 

If T is already a link (2nd line), the constant in const T is applied to the link, not to the referee. But the link is inherently constant in the sense that you cannot force it to refer to another object after initialization, so here const simply ignored. You can think of it as a "collapse" .; -)

+13
source

It:

 Foo<int&> f; 

leads to this instance:

 class Foo<int&> { public: void test(int&); void test(int&); }; 

const applies to a type that is a reference, is no-op. Compare it to a non-static member function acting on a referenced data element:

 struct A { int &ref; // valid: const member function doesn't treat "ref" as "const int&". void operate() const { ref = 0; } }; 

You must go int to Foo<...> in order to achieve your goal.

+8
source

In the second question, two copied functions have the same parameter type, and both are templates (if one of them is a template, the other is a function without a template, overload resolution selects a later one), so overload resolution will choose a template that will be more specialized. Usually const T & is a more specialized type than T &, so the first function of the template is called.

+1
source

All Articles