【问题标题】:Templated class in source file源文件中的模板类
【发布时间】:2015-10-23 16:36:18
【问题描述】:

从这个问题Storing C++ template function definitions in a .CPP file 移出,我尝试将模板化类的代码分开在头文件和源文件中。但是,我失败了,但我希望能对这种情况有所了解。请注意,与问题的不同之处在于他有一个模板化的函数,而不是一个类。

文件.h

template<typename T>
class A {
public:
    A();
private:
    T a;
};

文件.cpp

#include "file.h"

template<typename T>
A::A() { a = 0; }

template<int> class A;

和 main.cpp

#include "file.h"

int main() {
    A<int> obj;
    return 0;
}

和错误:

../file.cpp:4:1: error: invalid use of template-name ‘A’ without an argument list  A::A() { a = 0; }  
^ In file included from ../file.cpp:1:0: ../file.h:1:10: error: template parameter ‘class T’  template<typename T>
^ ../file.cpp:6:21: error: redeclared here as ‘int <anonymous>’  template<int> class A;
^ make: *** [file.o] Error 1

【问题讨论】:

    标签: c++ templates c++11 syntax compiler-errors


    【解决方案1】:

    像这样修改你的 .cpp 文件:

    template<typename T>
    A<T>::A() { a = 0; } // note the <T>
    
    template class A<int>;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-21
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多