I would like to define the explicit specialization of a template function in a cpp file. Is that possible? To be more concrete, I have the following code, which compiles without errors:
//class.h
class myclass
{
public:
/* Constructor */
myclass();
/* Trigger fcn */
template<typename T> T Trigger(T rn);
private:
/* Specializations of the templated Trigger(...) function */
template<> int Trigger<int>(int rn)
{
int_do(rn);
}
template<> double Trigger<double>(double rn)
{
double_do(rn);
}
}
However, I having the definitions in the header file looks weird for me, so I would like to separate the definitions from the declarations, something like this:
//class.h
class myclass
{
public:
/* Constructor */
myclass();
/* Trigger fcn */
template<typename T> T Trigger(T rn);
private:
/* Specializations of the templated Trigger(...) function */
template<> int Trigger<int>(int rn);
template<> double Trigger<double>(double rn);
}
and:
//class.cpp
/* Specializations of the templated Trigger(...) function */
template<> int myclass::Trigger<int>(int rn)
{
int_do(rn);
}
template<> double myclass::Trigger<double>(double rn)
{
double_do(rn);
}
Is there any way to to this?
Your only error is declaring the specialisations inside the class. Declare them in the header, but outside the class:
class myclass
{
public:
myclass();
template<typename T> T Trigger(T rn);
};
/* Specializations of the templated Trigger(...) function */
template<> int myclass::Trigger<int>(int rn);
template<> double myclass::Trigger<double>(double rn);
and then you can define them in a source file, exactly as you have done.
Note that your first snippet doesn't compile (unless your compiler has a non-standard extension), since the specialisations can't be declared inside the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With