【问题标题】:Can't explicitly instantiate a templated class [duplicate]无法显式实例化模板类 [重复]
【发布时间】:2020-09-11 11:41:10
【问题描述】:

在“header.h”中

template <typename T> struct Foo
{
    void func();
};

在“Source2.cpp”中

#include "Header.h"
#include <iostream>

template <typename T>
void Foo<T>::func()
{
    T a = 5;
    std::cout << a;;
}

在“Source1.cpp”中

#include "Header.h"

template struct Foo<int>;

int main()
{
    Foo<int> b;
    b.func();
}

链接器错误:函数 _main 中引用的 LNK2019 未解析的外部符号“public: void __thiscall Foo::func(void)”(?func@?$Foo@H@@QAEXXZ)

这不是显式实例化类的正确方法吗?

【问题讨论】:

  • 你编译正确吗?
  • func的定义必须在头文件中,而不仅仅是它的声明
  • @bruno 我认为显式实例化是一种可以用来在头文件中没有定义的方法
  • 您需要将显式实例化放在Source2.cpp中的方法实现之后。
  • @cigien 我明白了,为什么它不能按照我的方式工作?

标签: c++ template-classes


【解决方案1】:

模板方法的定义必须放在头文件中,关联的类允许编译器“扩展”它们(我使用“扩展”来简化,模板方法不是宏)

所以在 Header.h 中:

#include <iostream>
template <typename T> struct Foo
{
    void func();
};

template <typename T>
void Foo<T>::func()
{
    T a = 5;
    std::cout << a;
}

在“Source1.cpp”中

#include "Header.h"

template struct Foo<int>;

int main()
{
    Foo<int> b;
    b.func();
}

编译和执行(缺少std::cout &lt;&lt; std::endl; 以确保刷新并写入换行符):

pi@raspberrypi:/tmp $ g++ Source1.cpp 
pi@raspberrypi:/tmp $ ./a.out
5pi@raspberrypi:/tmp $ 

不要害怕 func 的“多个”定义,因为您在多个文件中使用相同的实例化,编译器/链接器会为您管理它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    相关资源
    最近更新 更多