[英]How to implement template specialization methods in *.cpp files?
1)通過CPP源文件中的模板化類實現方法:
//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>;
//主要
foo<int> foo;
foo.bar(42);
2)從CPP源文件中的類實現模板化方法:
//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);
//主要
foo toto;
toto.bar<int>(42);
3)實施專門的模板化方法...?
//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!
//主要
foo toto;
toto.bar<float>(42);
//編譯錯誤:
error LNK2019: unresolved external link "public: void __thiscall foo::bar<float>(float const &)" (??$bar@M@foo@@QAEXABM@Z) referenced in _main function
我無法解決此問題。
非常感謝您的幫助。
您的聲明不正確,應該是:
class foo
{
public:
template<typename T>
void bar(const T &t);
};
並在cpp文件中:
template <class T>
void foo::bar(const T &)
{
std::cout << "General." << std::endl;
}
template <>
void foo::bar<float>(const float &)
{
std::cout << "Float specialization." << std::endl;
}
template void foo::bar<int>(const int &);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.