Я изучаю программирование шаблонов и столкнулся с ошибкой, которую не могу понять.Моя задача состоит из 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 определяет функции классаtrial
#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;
}
Как я понимаю, отсюда "Неопределенная ссылка на" конструктор класса шаблона и 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
, компиляция запускается без ошибок и дает ожидаемые результаты.
Итак, мой вопрос (извините за длинное объяснение, так как я не мог объяснить свой вопрос более короткими словами), почему я не могу связать эти файлы вместе и чего мне не хватает?