【问题标题】:Templated Function definitions in seprate cpp file [duplicate]单独的 cpp 文件中的模板化函数定义[重复]
【发布时间】:2012-06-03 20:11:02
【问题描述】:

可能重复:
Why should the implementation and the declaration of a template class be in the same header file?
Do template class member function implementations always have to go in the header file in C++?

我在这里犯了一些愚蠢的错误,但我看不出是什么。

编译:

//start of header.h
namespace ns
{
    class A
    {
    public:
        template <class t>t func();
    };
    template<class t> t A::func()
    {
        t a;
        return a;
    }
}
//end of header.h

//imp.cpp的开始

//imp.cpp 结束

但以下不是:

//start of header.h
namespace ns
{
    class A
    {
    public:
        template <class t>t func();
    };
}
//end of header.h




//start of imp.cpp
#include "header.h"
using namespace ns;

template<class t> t A::func()
{
    t a;
    return a;
}

//imp.cpp 结束

错误是: 错误 LNK2019:函数 _main 中引用的未解析外部符号“public: int __thiscall ns::A::func(void)”(??$func@H@A@ns@@QAEHXZ)

【问题讨论】:

  • 这不是编译器错误,而是链接器错误。

标签: c++ templates


【解决方案1】:

模板必须在头文件中实现,因为它们在实例化之前无法编译。

看到这个答案: Why can templates only be implemented in the header file?

【讨论】:

    【解决方案2】:

    您应该阅读Storing C++ template function definitions in a .CPP file。模板专业化还有其他情况 - 它更像是普通函数(在 .hpp 中声明,在 .cpp 中定义)。如果您想在标题中进行专业化,您应该记住添加内联(因为 ODR)。

    http://en.wikipedia.org/wiki/One_Definition_Rule[ODR][1]

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多