![](/img/trans.png)
[英]:: scope resolution operator in front of a template function call in c++
[英]Need scope resolution operator to call member function template when class template exists with same name
我有一個類模板碰巧與某些類的成員函數模板具有相同的名稱。 現在,另一個函數模板將使用其中一個具有相關成員函數模板的類進行實例化。 要在此函數模板中調用成員函數模板,我需要使用template
關鍵字,我理解這一點並且沒有問題。 但是,我需要使用范圍解析運算符(我剛剛發現那就是所謂的) ::
指定我的意思是類的成員函數模板而不是類模板,我不明白為什么。
這是很多模板化的事情,所以讓我舉一個例子:
//class with same name as member function below.
//must be class template or error doesn't show up.
//also no error if this is a function template instead of class
template <class T>
struct f
{
};
struct Base
{
//function with same name as struct above,
//no error if this is not templated
template <int N>
void f(){}
};
//template function that will be instantiated with T=Base.
//no error if this is not templated
template <class T>
void g(T t)
{
//I understand why template keyword is needed here,
//but not why T:: is needed
t.T::template f<0>();
//t.template f<0>(); gives error.
}
有問題的錯誤是(來自g ++ - 4.7)
error: type/value mismatch at argument 1 in template parameter list for ‘template<class T> struct f’
error: expected a type, got ‘0’
似乎編譯器在注釋掉的行(沒有作用域解析運算符f<0>()
上解析f<0>()
,試圖實例化struct f<0>
類型的對象。 我不知道為什么會這樣做,我認為它應該能夠從t.template
看到我正在嘗試訪問成員函數模板。
我想了解這里發生了什么,為什么在這種情況下需要T::
除了安撫編譯器?
似乎在MSVC和Clang下沒有問題,所以它似乎是一個特定於g ++的問題。
我認為這與兩階段查找有關 。 特別是Steve Jessops在答案中的注意事項很重要。
這可能會奏效
template <class T>
void g(T t)
{
t.T::template f<0>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.