Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specialization of template member functions of a non-template class

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?

like image 942
Iban Avatar asked Dec 04 '13 11:12

Iban


1 Answers

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.

like image 94
Mike Seymour Avatar answered Sep 24 '22 08:09

Mike Seymour