gpt4 book ai didi

c++ - 对模板基类成员函数的 undefined reference

转载 作者:搜寻专家 更新时间:2023-10-31 02:24:17 25 4
gpt4 key购买 nike

考虑以下代码:

我的类.h :

template <class T>
struct S {
void f();
};

struct MyClass : public S<int>
{
void g();
};

我的类.cpp :

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

template <class T>
void S<T>::f()
{
std::cout << "f()\n";
/* some code here that could not be in header */
}

void MyClass::g()
{
std::cout << "g()\n";
}

main.cpp :

#include "myclass.h"

int main()
{
MyClass m;
m.g();
m.f(); // problem here
}

我有链接器错误:

undefined reference to `S::f()'

我可以在不将 S::f() 的实现转移到头文件的情况下解决这个问题吗?为什么当我声明从完全专用模板基类派生的 MyClass 时,S::f() 没有实例化?

最佳答案

Why S::f() not instantiated when I declare a MyClass derived from full specialized template base class?

因为您的 myclass.cpp 没有使用该模板,并且像翻译单元中所有未使用的模板一样,它们在生成的代码中毫无意义。推导一切顺利,如果MyClass::g()二手 S<T>::f()您将引入该代码,生活会很美好。但是你没有,所以你必须用另一种方式拉它......

你应该能够通过显式实例化来做到这一点。请注意您的 .cpp 文件中的以下内容:

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

template <class T>
void S<T>::f()
{
std::cout << "f()\n";
}

void MyClass::g()
{
std::cout << "g()\n";
}

template struct S<int>; // ADDED

但是请注意。这仅在唯一用法是 S<int> 时才有效.额外的扩展将需要额外的显式实例化条目。

您也可以通过直接特化来做到这一点,例如将您的 .cpp 更改为只执行此操作:

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

template <>
void S<int>::f()
{
std::cout << "f()\n";
}

void MyClass::g()
{
std::cout << "g()\n";
}

但这在我看来是相当有限的,因为您添加的每个额外类型都需要自己的特化。

无论如何,祝你好运。

关于c++ - 对模板基类成员函数的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28212558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com