'How to implement template specialization methods in *.cpp files?
1) Implement methods from a templated class in a CPP source file:
//foo.hpp
template<typename T>
class foo
{
public:
void bar(const T &t);
};
//foo.cpp
template <class T>
void foo<T>::bar(const T &t)
{
std::cout << "General." << std::endl;
}
template class foo<int>;
//main
foo<int> foo;
foo.bar(42);
2) Implement templated methods from a class in a CPP source file:
//foo.hpp
class foo
{
public:
template<typename T>
void bar(const T &t);
};
//foo.cpp
template <class T>
void foo::bar(const T &t)
{
std::cout << "General." << std::endl;
}
template void foo::bar<int>(const int &t);
//main
foo toto;
toto.bar<int>(42);
3) Implement specialized templated method... ?
//foo.hpp
class foo
{
public:
template<typename T>
void bar(const T &t);
template<>
void bar<float>(const float &t);
};
//foo.cpp
template <class T>
void foo::bar(const T &t)
{
std::cout << "General." << std::endl;
}
template <>
void foo::bar<float>(const float &t)
{
std::cout << "Float specialization." << std::endl;
}
template void foo::bar<int>(const int &t);
template void foo::bar<float>(const float &t); //Seems to be not correct!
//main
foo toto;
toto.bar<float>(42);
//Compilation error:
error LNK2019: unresolved external link "public: void __thiscall foo::bar<float>(float const &)" (??$bar@M@foo@@QAEXABM@Z) referenced in _main function
I can't reach the solution to this problem.
Thanks very much in advance for your help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
