Reputation: 2920
I would like to define a templated class
CTest<T>
in which one of the methods can return an object of type
CTest<U>
with T not necessarily equal to U, as follows:
template<typename T>
class CTest {
// Properties
private:
T Prop_1;
// Methods
public:
CTest::CTest (T);
CTest::~CTest ();
template<typename U>
CTest<U> Method_1 (U);
};
template<typename T>
CTest<T>::CTest (T _Prop_1) {
this->Prop_1 = _Prop_1;
}
template<typename T>
CTest<T>::~CTest () {
}
template<typename T, typename U>
CTest<U> CTest<T>::Method_1 (U _P) {
CTest<U> Result (_P);
return Result;
}
Actually, I've also tried defining Method_1 in the following way:
template<typename T>
template<typename U>
CTest<U> CTest<T>::Method_1 (U _P) {
return CTest<U> (_P);
}
I tried to consume the class as follows:
int main () {
CTest<int> Test (1);
auto Test_2 = Test.Method_1<float> (2.0);
return 0;
}
But I keep getting the compile-time error "unable to match function to an existing declaration." Thanks in advance for your help.
Upvotes: 1
Views: 689
Reputation: 154045
It seems your primary problem are the constructor and destructor in the class definition: these should use extra qualification. Removing this junk causes the code to compiler for me with all compilers I have (gcc, clang, and EDG; for the latter I needed to remove auto Test 2 =
). Here is the exact code I compiled:
template<typename T>
class CTest {
private:
T Prop_1;
public:
CTest (T);
~CTest ();
template<typename U> CTest<U> Method_1 (U);
};
template<typename T>
CTest<T>::CTest (T _Prop_1) {
this->Prop_1 = _Prop_1;
}
template<typename T>
CTest<T>::~CTest () {
}
template<typename T>
template<typename U>
CTest<U> CTest<T>::Method_1 (U _P) {
return CTest<U> (_P);
}
int main () {
CTest<int> Test (1);
auto Test_2 = Test.Method_1<float> (2.0);
return 0;
}
Upvotes: 2