【发布时间】:2019-11-06 16:19:35
【问题描述】:
我理解了模板的概念以及为什么我们需要在头文件中定义模板成员函数。另一种选择是在 cpp 文件中定义模板函数并显式实例化模板类,如下所示。
template.h
#include <iostream>
using namespace std;
template <typename T> class myclass
{
public:
void doSomeThing();
};
template.cpp
#include <iostream>
#include "template.h"
using namespace std;
template <typename T> void myclass<T>::doSomeThing()
{
cout << "in DoSomething" << endl;
}
template class myclass <int>; // Why we shouldn't use template<> class myclass <int> here?
main.cpp
#include <iostream>
#include "template.h"
using namespace std;
int main()
{
myclass<int> obj;
obj.doSomeThing();
}
我正在使用 g++ main.cpp template.cpp 在 Ubuntu 操作系统上编译,我可以调用 doSomeThing()
我有几个问题如下。
- 如果我们需要显式实例化类模板,应该是
template <> class myclass <int>但是当我在 template.cpp 而不是template class myclass <int>,它是 抛出对'myclass::doSomeThing()'的未定义引用 错误。为什么我们不应该在这种情况下使用<>? -
我尝试将 myclass(用于 int)的对象实例化为
myclass <int> obj;而不是template <> class myclass <int>;in template.cpp 如下。#include <iostream> #include "template.h" using namespace std; template <typename T> void myclass<T>::doSomeThing() { cout << "in DoSomething" << endl; } myclass <int> obj;我认为 template.cpp 有通过 template.h 的模板声明和 template.cpp 中的所有模板函数定义,所以为 int 类型创建一个对象将为 int 创建一个类,它将包含 int 类型的函数定义。因此,当 g++ 编译 main.cpp 时,它具有 int 类型的所有功能,并且如果我先编译 template.cpp 并在
g++ template.cpp main.cpp之后编译 main.cpp,则为 myclass(用于 int 数据类型)创建对象将起作用。但这也会引发 main.cpp:(.text+0x1f): undefined reference to `myclass::doSomeThing()' 错误。我无法理解为什么这会引发错误。谁能帮我理解为什么这不起作用。
【问题讨论】:
-
如果我们需要显式实例化类模板,应该是
template <> class myclass <int>为什么?谁告诉你的?
标签: c++