2017-05-21 163 views
0
#include <iostream>                            
#include <string>                             

using namespace std;                            

template <typename T,                            
      typename T::type N,                          
      typename T::strata& X>                         
struct SomeClass{};                            

struct S1                               
{                                 
    typedef int type;                            
    typedef string strata;                           
};                                 

int main() {                              
    SomeClass<S1, 3, string("erg")> x;                        
}  

失敗消息:非類型模板參數沒有引用任何聲明?

g++ templ.cc -o templ -std=c++14                     
templ.cc:18:20: error: non-type template argument does not refer to any declaration            
    SomeClass<S1, 3, string("erg")> x;                        
        ^~~~~~~~~~~~~                         
templ.cc:8:24: note: template parameter is declared here                   
      typename T::strata& X> 

爲什麼它的工作原理爲INT而不是字符串? 爲什麼它說該字符串是非類型的參數?

+0

因爲它不是一個類型。非類型參數僅限於基元(實際上,積分和指針) –

+2

@PasserBy也可以使用此處所用的類類型引用。 – aschepler

+0

而且...我沒有看到那個參考:) –

回答

4

模板參數是一個值,而不是一個類型或模板,簡單地稱爲「非類型模板參數」。

由於參考文獻而失敗。如果您有typename T::type& N,您會在3上看到類似的錯誤。

引述cppreference.com

以下限制實例具有非類型模板參數模板時適用:

  • 對於左值參考的參數,在實例中提供的參數不能是暫時的,一個未命名的左值或一個沒有鏈接的命名左值(換句話說,參數必須有鏈接)。

所以你的臨時無效。但你可以這樣做:

std::string erg("erg"); 
int main() {                              
    SomeClass<S1, 3, erg> x;                        
} 
+0

爲什麼如果我在main()中放入字符串,它會抱怨「沒有鏈接」? –

+4

由於具有自動存儲持續時間的變量沒有鏈接。 – aschepler