Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template function's priority is different between vs2005 and vs2010

class Foo
{
 friend class SquirrelVM;
public:
 Foo() { cout << "Ctor" << endl; }
 virtual ~Foo() { cout << "Dtor" << endl; }
 Foo(const Foo & o) { cout << "const Ctor" << endl; }

 template <typename _ty>
 Foo(const _ty & val) { cout << "T const Ref" << endl; }
 template <typename _ty>
 Foo(_ty & val) { cout << "T Ref" << endl; }
 template <typename _ty>
 Foo(_ty * val) { cout << "T Ptr" << endl; }
};

Foo CreateFoo()
{
 Foo ret;
 return ret;
}

int main( int argc, char* argv[] )
{
 Foo f = CreateFoo(); 
 return 0;
}

Outputs are different between vs2005 and vs 2010. Expected outputs are like this..

Ctor
const Ctor
Dtor
Dtor

Above outputs are derived if I build in vs2005.

But, vs2010's output is not same with vs2005's

Ctor
T Ref
Dtor
Dtor

Why template function's priority is higher than normal function in vs2010?


[edit] If const is ommitted on copy constructor, than expected output(which is same with vs2005) comes out. Is there any side effect if form of copy constructor is not same with recomended form? Recomended form.. I mean... Foo(const Foo&); not Foo(Foo&);

like image 641
codevania Avatar asked Dec 13 '10 10:12

codevania


1 Answers

Foo(_ty & val) with _ty being Foo is a better match because it will have parameter type Foo& matching a non-const Foo lvalue, while the other has a const that will make it a bit worse match.

There was some confusion during the made-up process of C++0x and before as to whether templates can be used to copy an object of a class to its own class type. The committee just recently figured they want to stop the confusion about it and allow such a thing. VS2010 seems to reflect that decision.

like image 129
Johannes Schaub - litb Avatar answered Sep 28 '22 06:09

Johannes Schaub - litb