繁体   English   中英

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

[英]Compile template class failed by g++ or 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 ++规范不兼容吗? 是那些熟悉编译器的人,不是吗?

根据ISO C ++标准的大写字母,GCC和Clang是正确的:

[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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM