【发布时间】:2013-05-09 12:48:15
【问题描述】:
我有一个类模板,它恰好与某些类的成员函数模板同名。现在,另一个函数模板被实例化为具有相关成员函数模板的类之一。要在这个函数模板中调用成员函数模板我需要使用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>() 解析为试图实例化struct f<0> 类型的对象。不知道为什么会这样,我想应该可以从t.template看到我正在尝试访问成员函数模板。
我想了解这里发生了什么,为什么在这种情况下需要T::,而不是为了安抚编译器?
MSVC和Clang下好像没有问题,所以好像是g++特有的问题。
【问题讨论】: