【问题标题】:Template ctor mssing模板 ctor 缺失
【发布时间】:2022-01-08 20:09:41
【问题描述】:

我认为答案很简单,但我无法找到解决方案。

我有一个类用作 h 文件中的接口:

template <typename T>
class MyInterface
{
public:
  MyInterface();
};

在 cpp 文件中是:

#include "MyInterface.h"
template<typename T>
MyInterface<T>::MyInterface()
{
}

我使用该接口的类是:

class Test : MyInterface<int>
{
};

编译时出现错误,未声明 MyInterace 的 ctor。

函数“public: __thiscall Test::Test(void)”中引用的未解析外部符号“public: __thiscall MyInterface::MyInterface(void)”(??0?$MyInterface@H@@QAE@XZ)

在 h 文件中声明了 ctor,它就可以编译了。

【问题讨论】:

标签: c++ templates constructor


【解决方案1】:

模板是动态实例化的。如果要将构造函数放在cpp 文件中,则必须对其进行专门化。

#include "MyInterface.h"
template<>
MyInterface<int>::MyInterface()
{
}

否则,它必须在标题中,因为所有模板函数都是内联管理的。

如果您想保持代码井井有条,请创建一个 inl 文件,其中包含代码的所有函数体,然后将其包含在标题的底部。

// MyInterface.h
template <typename T>
class MyInterface
{
public:
  MyInterface();
};

#include "MyInterface.inl"
// MyInterface.inl
template<class T>
MyInterface<T>::MyInterface()
{
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多