我正在学习模板编程,遇到了一个我无法理解的错误。我的任务涉及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
编译运行时没有错误,并按预期提供结果。
所以我的问题是(抱歉,我不能用简短的语言解释我的问题),为什么我不能将这些文件链接在一起,我遗漏了什么?