2017-05-25 56 views
7

模板函數在模板類隨着</p> <pre><code>template <typename T> class Foo { public: template <int x> void bar() {} }; </code></pre> <p>以下編譯

void fooBar() 
{ 
    Foo<int> f; 
    f.bar<1>(); 
} 

但以下不(用「錯誤:前預期主表達式‘)’標記」中的gcc 5.4 .0與-std = C++ 14)。

template <typename T> 
void fooBar() 
{ 
    Foo<T> f; 
    f.bar<1>(); 
} 

如果我嘗試明確調用第二個版本,例如,

fooBar<int>(); 

然後GCC還抱怨

"invalid operands of types '<unresolved overloaded function type>' and 'int' to binary 'operator<'". 

是否有任何理由爲什麼第二個版本是無效的?爲什麼gcc將'<'視爲一個運算符而不是模板參數列表的開始?

+0

的功能是什麼'FOO <>()幫助編譯器;'?它存在於哪裏? – alhadhrami

+0

@alhadhrami對不起 - 應該閱讀fooBar。在編輯中更正。 – Matt

回答

15

有了模板函數,編譯器不知道到底是什麼Foo<T>會(有可能是Foo特例),因此它必須假設f.bar是一個成員變量,並解析代碼

f.bar < 1 

然後它不能繼續。

你可以告訴它bar是一個模板

f.template bar<1>(); 
+0

這有用 - 我從來沒有見過這種語法。我永遠不會想到這樣做。謝謝! – Matt

相關問題