![](/img/trans.png)
[英]Specialized template function with deleted “general” case fails to compile with g++ <=4.8.0 and 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是正確的:
如果聲明包含初始化程序,則模板的靜態數據成員的顯式專業化或靜態數據成員模板的顯式專業化是定義。 否則,它是一個聲明。 [注意:需要默認初始化的模板的靜態數據成員的定義必須使用大括號初始化列表:
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.