我有一个类模板碰巧与某些类的成员函数模板具有相同的名称.现在,另一个函数模板将使用其中一个具有相关成员函数模板的类进行实例化.要在此函数模板中调用成员函数模板,我需要使用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下没有问题,所以它似乎是一个特定的问题.
解决方法
我认为这与
Two phase lookup有关.特别是Steve Jessops在答案中的注意事项很重要.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。