0

当我有一个可以归结为这样的课程时:

// test.hpp
class Test{
public:
  template<typename T> static T value;
};

template<typename T> Test::value = {};

value当我只在一个 .cpp 文件中查找实例时,我可以使用这个类。但是当我尝试在多个 .cpp 文件中使用它时,我得到一个已经定义的链接器错误。

//somefile1.cpp
include "test.hpp"
void fn(){
  int i = Test::value<int>;
}

// somefile2.cpp
include "test.hpp"
void otherfn(){
  // public static int value already defined in somefile1.obj
  int j = Test::value<int>;
}

放入template<typename T> Test::value = {}其自己的 .cpp 文件会为所有用途提供未解决的外部错误。有什么问题?

4

0 回答 0