【发布时间】:2016-08-05 19:14:35
【问题描述】:
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
我无法解决这个问题。
非常感谢您的帮助。
【问题讨论】:
-
stackoverflow.com/questions/495021/… 在这里不适用吗?
标签: c++ templates visual-c++