I would like to know is there a way to identify template argument? For example, let say I want to initialize a variable based on template argument. Prototype example is as follow
template<class T>
void initialise(T a)
{
if(T==int)a=0;
else if(T=double)a=0.0;
else if(T=complex<double>)a=T(0.,0);
else print("unknown type");
}
My question is how to identify that template argument "T"? Or, do I need to take help of preprocessor directives? It might be a repetitive question, but I didn't find its answer. Any kind of suggestions will be appreciated.
This is how you would "re-set" an argument to zero using a function template:
template<class T>
void initialise(T& a)
{
a = T(); // or T{};
}
If you want to restrict it to arithmetic types, you can use SFINAE and std::is_arithmetic
(floating point and integral types), plus a specialization for std::complex
.
template<class T>
typename enable_if<std::is_arithmetic<T>::value, void >::type
void initialise(T& a)
{
a = T();
}
template<class T>
void initialise(std::complex<T>& a)
{
a = T();
}
You can use template specializations. Something like that:
template<class T>
void initialise(T a)
{
print("unknown type");
}
template<>
void initialise<int>(int a)
{
a=0;
}
template<>
void initialise<double>(double a)
{
a=0.0;
}
template<>
void initialise<complex<double>>(complex<double> a)
{
a=complex<double>(0.,0);
}
Of course, those functions do not make much sense, but I guess it is due to the fact that you tried to propose a minimal example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.