【发布时间】:2018-12-06 07:19:08
【问题描述】:
我正在学习模板编程,但遇到了一个我无法理解的错误。我的任务涉及 3 个文件 1) 一个主文件(带主函数)
#include<iostream>
#include "templates.h"
int main(){
trial <int>x;
x.input(3);
std::cout<<x.ret();
return 0;
}
2) 头文件
#ifndef templ
#define templ
template<typename T>
class trial{
T val;
public:
void input(T x);
T ret();
};
#include "templateref.cpp"
#endif
3) 一个.cpp文件用于定义类试验的功能
#ifndef templ
#define templ
#include"templates.h"
#endif
template<class T>
void trial<T>::input(T x){
val = x;
return ;
}
template<class T>
T trial<T>::ret(){
return val;
}
因为我从这里不知道 "Undefined reference to" template class constructor 和 https://www.codeproject.com/Articles/48575/How-to-define-a-template-class-in-a-h-file-and-imp 我必须实例化模板类才能工作。
当我尝试编译它时出现了我的问题。 当我这样做时
clang++ templates.cpp templateref.cpp -Wall -o template
我得到了错误
templateref.cpp:14:6: error: variable has incomplete type 'void'
void trial<T>::input(T x){
^
templateref.cpp:14:11: error: expected ';' at end of declaration
void trial<T>::input(T x){
^
;
templateref.cpp:14:11: error: expected unqualified-id
templateref.cpp:20:11: error: qualified name refers into a specialization of variable template 'trial'
T trial<T>::ret(){
~~~~~~~~^
templateref.cpp:14:6: note: variable template 'trial' declared here
void trial<T>::input(T x){
^
4 errors generated.
这是由
修复的clang++ templates.cpp -Wall -o template
编译运行没有错误,并给出了预期的结果。
所以我的问题是(对不起,解释太长了,因为我无法用更短的词来解释我的问题)为什么我不能将这些文件链接在一起,我错过了什么?
【问题讨论】:
-
您还需要将模板化的函数放在标题中。
-
它们是头文件中定义的类的成员函数,所以我现在只能提供该函数的定义
-
是的,因为
<T>实际上是函数签名的一部分,所以在模板用户提供类型之前无法编译它——所以,把它们放在头文件中。