* Deep:
Can I use a class in this manner, where a constructor is of templated:
template<typename T>
class my_class{
public:
int x_;
public:
template<typename U>
my_class(const my_class<U>& other ) : x_(other.x_){}
};
please guide me...
You can use templated constructors, but a templated constructor is never
formally a copy constructor. Therefore, the compiler may generate a
copy constructor, and use that, if copying of same type is invoked.
This is difficult to test because the compiler is generally allowed to
remove copy constructor calls even if the copy constructor has some side
effect.
Also, you need some other constructor in order to create any object in
the first place.
You can try (although output from the copy constructor is not guaranteed)
#include <iostream>
#include <ostream>
void say( char const s[] ) { std::cout << s << std::endl; }
template<typename T>
class MyClass1
{
public:
int x_;
public:
MyClass1(): x_( 0 ) {}
template<typename U>
MyClass1( MyClass1<U> const& other ): x_( other.x_ )
{ say( "Template constructor 1." ); }
};
template<typename T>
class MyClass2
{
public:
int x_;
public:
MyClass2(): x_( 0 ) {}
template<typename U>
MyClass2( MyClass2<U> const& other ): x_( other.x_ )
{ say( "Template constructor 2." ); }
MyClass2( MyClass2 const& other ): x_( other.x_ )
{ say( "Copy constructor 2." ); }
};
typedef MyClass1<int> Class1;
typedef MyClass2<int> Class2;
void foo( Class1 ) { say( "foo 1" ); }
void foo( Class2 ) { say( "foo 2" ); }
int main()
{
Class1 o1;
foo( o1 );
Class2 o2;
foo( o2 );
}