F
ferdinand.stefanus
Hi, I have some questions regarding templated class constructor:
#include <iostream>
using namespace std;
template<typename T>
class Foo
{
public:
explicit Foo(const T& bar): _bar(bar)
{ cout << "In constructor, _bar = " << _bar << '\n'; }
template<typename U>
Foo(const Foo<U>& rhs): _bar(rhs.GetBar())
{ cout << "In converting constructor, _bar = " << _bar << '\n'; }
Foo(const Foo<T>& rhs): _bar(rhs._bar)
{ cout << "In copy constructor, _bar = " << _bar << '\n'; }
T GetBar() const { return _bar; }
private:
T _bar;
};
int main()
{
Foo<int> intFoo1(1), intFoo2(2);
Foo<int> intFoo3(intFoo1);
Foo<double> dblFoo1(intFoo2);
}
A quick test with VC++6 yields the following result:
In constructor, _bar = 1
In constructor, _bar = 2
In copy constructor, _bar = 1
In converting constructor, _bar = 2
Is this behaviour conforming with the standard? It seems that even if I
remove the copy constructor declaration/definition, the converting
constructor will not be used (the compiler-generated copy constructor
will be used instead). If that's the case, can I safely assume that the
converting constructor will never be called for templated class of the
same type?
Thanks!
#include <iostream>
using namespace std;
template<typename T>
class Foo
{
public:
explicit Foo(const T& bar): _bar(bar)
{ cout << "In constructor, _bar = " << _bar << '\n'; }
template<typename U>
Foo(const Foo<U>& rhs): _bar(rhs.GetBar())
{ cout << "In converting constructor, _bar = " << _bar << '\n'; }
Foo(const Foo<T>& rhs): _bar(rhs._bar)
{ cout << "In copy constructor, _bar = " << _bar << '\n'; }
T GetBar() const { return _bar; }
private:
T _bar;
};
int main()
{
Foo<int> intFoo1(1), intFoo2(2);
Foo<int> intFoo3(intFoo1);
Foo<double> dblFoo1(intFoo2);
}
A quick test with VC++6 yields the following result:
In constructor, _bar = 1
In constructor, _bar = 2
In copy constructor, _bar = 1
In converting constructor, _bar = 2
Is this behaviour conforming with the standard? It seems that even if I
remove the copy constructor declaration/definition, the converting
constructor will not be used (the compiler-generated copy constructor
will be used instead). If that's the case, can I safely assume that the
converting constructor will never be called for templated class of the
same type?
Thanks!