Consider the following implementation of a template class:
template<class T>
class MyClass
{
public:
void setVar1(const T& v1)
{
var1 = v1;
}
void setVar2(const T1& v2)
{
var2 = v2;
}
T var1;
T1 var2;
};
If the template parameter T
is a fundamental type (like float
, double
, or long double
) I would like to have T1 = T
.
If the template parameter T
is std::complex<float>
, I would like to have T=std::complex<float>
and T1 = float
. Similarly for std::complex<double>
and std::complex<long double>
.
Deducing the type of the variable is discussed at Template type derivation
However, the additional member functions prevents usage of their solution in this context.
Based on Bo Personns comment and the answer provided at https://stackoverflow.com/questions/47334675/template-type-derivation
I got the following working example.
The content of my .h file is as follows.
The .cpp file contains the following lines of code.
The above code works as intended.
However, I have another related question posted at Template type deduction in function return type
A custom traits class would suffice. You can leverage partial specializations to select the type you want/need. Example code
Live Example
There are many other ways though.