代码之家  ›  专栏  ›  技术社区  ›  Niteya Shah

将多个文件与另一个.cpp文件中的模板类链接

  •  -2
  • Niteya Shah  · 技术社区  · 6 年前

    我正在学习模板编程,遇到了一个我无法理解的错误。我的任务涉及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
    

    编译运行时没有错误,并按预期提供结果。

    所以我的问题是(抱歉,我不能用简短的语言解释我的问题),为什么我不能将这些文件链接在一起,我遗漏了什么?

    1 回复  |  直到 6 年前
        1
  •  1
  •   molbdnilo    6 年前

    您不应该编译成员定义文件“它已经包含在头中”。

    由于该文件中的include保护,编译器处理它时将排除整个头,并且类模板定义不存在。

    只需编译主文件。