g ++或clang ++编译模板类失败

时间:2017-11-22 06:34:07

标签: c++ templates g++ clang++

我编写的源代码如下所示。 ----- sample.h ------

#include <iostream>
template <typename T>
class Sample {
private:
static int foo;
public:
 Sample (T number) {
foo = number;}
 void display () {
std :: cout << foo << std :: endl;}
};

---- test.cpp --------------

#include "sample.h"
template <> int Sample <float> :: foo;


int main () {
 Sample <float> test (100.9);
 test.display ();
 return 0;
}

我已成功使用Visual Studio 2015社区编译。 但是,g ++和clang ++(ubuntu linux 16.04 LTS)在链接时失败了。 我想用g ++或clang ++编译,所以我想做点什么, 我不是一个好主意。 它与g ++或clang ++规范不兼容吗? 那些熟悉编译器的人不是吗?

1 个答案:

答案 0 :(得分:1)

根据ISO C ++标准的干信,GCC和Clang是正确的:

[temp.expl.spec]/13

  

模板或静态数据成员的显式特化   静态数据成员模板的显式特化是一个   如果声明包含初始化程序,则定义;否则,它   是宣言。 [注意:静态数据成员的定义   需要默认初始化的模板必须使用a   支撑-INIT-列表:

template<> X Q<int>::x;                         // declaration
template<> X Q<int>::x ();                      // error: declares a function
template<> X Q<int>::x { };                     // definition
     

- 结束说明]

当应用于您的示例时,意味着您只提供另一个声明,而不是定义。修复方法是添加初始化程序:

template <> int Sample <float> :: foo{}; // Default initialize `foo`

template <> int Sample <float> :: foo{0.0}; // Direct initialize `foo` to 0

template <> int Sample <float> :: foo = 0.0; // Copy initialize `foo` to 0
相关问题