2015-09-19 60 views
-1

下面的代碼編譯在鐺細++ -std = C++ 1Y,其中如在同一克給予錯誤++ -std = C++ 1Y外部鏈接模板對象eror

#include <iostream> 
using namespace std; 

class Demo { 
public: 
    Demo(){} 
}; 


template <Demo const &ref> 
void fun(){} 


Demo g; 
const Demo g_c; 

int main(){ 
    fun<g>(); 
    fun<g_c>(); 

}; 

下面克錯誤++

error: the value of ‘g_c’ is not usable in a constant expression 
    fun<g_c>(); 
    ^
error: ‘g_c’ is not a valid template argument for type ‘const Demo&’  because object ‘g_c’ has not external linkage 
    fun<g_c>(); 
    ^

const Demo g_c;
有內部聯繫權嗎?這是否意味着g ++在我的分析中有bug或錯誤?

+0

可能重複http://stackoverflow.com/問題/ 9218615 /函數模板與參考模板參數) – BartoszKP

回答

2

const Demo g_c;
有內部聯繫權嗎?

正確。一個(非本地)const限定對象具有內部鏈接,除非該聲明或更早的聲明明確給出了它的外部鏈接。

這是否意味着g ++在我的分析中有bug或錯誤?

您的分析肯定是錯誤的。 GCC的錯誤是告訴你,對象的引用不能用作模板參數,除非這些對象具有外部鏈接。你的對象沒有外部鏈接,所以GCC的錯誤與它實際檢查的內容相符。

但它也意味着g ++有一個錯誤。它執行的規則來自C++ 03。 C++ 11放寬了規則,你的代碼現在是有效的。這是a known bug

您可以通過給你的對象外部鏈接解決它:

extern const Demo g_c; 
const Demo g_c; 

extern const Demo g_c {}; 
[功能與參考模板參數模板(的