Specialization of functions of a member of a class template without a template

I would like to define an explicit specialization of the template function in the cpp file. Is it possible? To be more specific, I have the following code that 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 strange to 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 do this?

+4
source share
2 answers

Your only mistake is declaring specializations within a 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 the source file, just like you did.

, ( ), .

+8

:

.cpp. , / . .h, .

, file tmp.h:

#include <iostream>
class T {
public:
  template <typename T> void foo(const T& t)
  {
    std::cout << "generic foo" << std::endl;
  }
};
// forward declaration of specialization
template<> void T::foo(const double& t);

file tmp.cpp:

#include "tmp.h"

template <> void T::foo(const double& t)
{
  std::cout << "double foo" << std::endl;
}

file main.cpp:

#include "tmp.h"
int main(int argc, const char** argv)
{
  T t;
  t.foo(1.0); 
  t.foo(1);
  return 0;
}

.cpp :

g++ main.cpp tmp.cpp -o tmp
./tmp
double foo
generic foo

:

g++ main.cpp -o tmp
/tmp/ccpCJr3B.o: In function `main':
main.cpp:(.text+0x1f): undefined reference to `void T::foo<double>(double const&)'
collect2: error: ld returned 1 exit status
+1

All Articles