编译模板类因G 或Clang 而失败

Compile template class failed by g++ or clang++

本文关键字:Clang 失败 编译      更新时间:2023-10-16

我编写了源代码,如下所示。-----样本。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 规格兼容吗?那些熟悉编译器的人,不是吗?

gcc和clang是根据ISO C 标准的干燥字母正确的:

[temp.expl.spec]/13

模板或模板的静态数据成员的明确专业化 静态数据成员模板的明确专业化是一个 定义如果声明包括初始化器;否则,它 是声明。[注意:静态数据成员的定义 需要默认限制的模板必须使用 支撑列表:

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
相关文章: