【问题标题】:How to implement template specialization methods in *.cpp files?如何在 *.cpp 文件中实现模板特化方法?
【发布时间】: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

我无法解决这个问题。

非常感谢您的帮助。

【问题讨论】:

标签: c++ templates visual-c++


【解决方案1】:

你的声明不正确,应该是:

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 &);

【讨论】:

  • 好的!非常感谢您的帮助!再见。
猜你喜欢
  • 2014-06-25
  • 1970-01-01
  • 1970-01-01
  • 2022-06-18
  • 2015-02-03
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多