[英]Compile template class failed by g++ or clang++
I wrote the source code as shown below. 我编写了如下所示的源代码。 ----- sample.h ------
----- 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 -------------- ---- test.cpp --------------
#include "sample.h"
template <> int Sample <float> :: foo;
int main () {
Sample <float> test (100.9);
test.display ();
return 0;
}
I have successfully compiled with Visual Studio 2015 community. 我已成功使用Visual Studio 2015社区进行了编译。 However, g++ and clang++ (ubuntu linux 16.04 LTS) failed at linking time.
但是,g ++和clang ++(ubuntu linux 16.04 LTS)在链接时失败。 I want to compile with g++ or clang++, so I'd like to do something, I do not get a good idea.
我想用g ++或clang ++进行编译,所以我想做点什么,我没有一个好主意。 Is not it compatible with g++ or clang++ specifications?
它与g ++或clang ++规范不兼容吗? Are those who are familiar with the compiler, are not you?
是那些熟悉编译器的人,不是吗?
GCC and Clang are correct according to the dry letter of the ISO C++ standard: 根据ISO C ++标准的大写字母,GCC和Clang是正确的:
[temp.expl.spec]/13 [temp.expl.spec] / 13
An explicit specialization of a static data member of a template or an explicit specialization of a static data member template is a definition if the declaration includes an initializer;
如果声明包含初始化程序,则模板的静态数据成员的显式专业化或静态数据成员模板的显式专业化是定义。 otherwise, it is a declaration.
否则,它是一个声明。 [ Note: The definition of a static data member of a template that requires default-initialization must use a braced-init-list:
[注意:需要默认初始化的模板的静态数据成员的定义必须使用大括号初始化列表:
template<> X Q<int>::x; // declaration template<> X Q<int>::x (); // error: declares a function template<> X Q<int>::x { }; // definition
— end note ]
—尾注]
Which when applied to your example means you just provide another declaration, not a definition. 将其应用于您的示例意味着您仅提供了另一个声明,而不是定义。 And a fix would be to add an initializer:
解决方法是添加一个初始化程序:
template <> int Sample <float> :: foo{}; // Default initialize `foo`
Or 要么
template <> int Sample <float> :: foo{0.0}; // Direct initialize `foo` to 0
Or 要么
template <> int Sample <float> :: foo = 0.0; // Copy initialize `foo` to 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.