c++ - 当同名类模板存在时,需要范围解析运算符调用成员函数模板

标签 c++ g++

我有一个类模板恰好与某些类的成员函数模板同名。现在另一个函数模板被实例化为其中一个具有相关成员函数模板的类。要在此函数模板中调用成员函数模板,我需要使用 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++特有的问题。

最佳答案

我认为这与 Two phase lookup 有关. Steve Jessops 在答案中的注释尤其重要。

关于c++ - 当同名类模板存在时,需要范围解析运算符调用成员函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16556723/

相关文章:

c++ - 类能否在其成员初始化列表中初始化其非立即基类?

c++ - 如何通过编译时 "if"返回 T 值?

c++ - 射线与椭球相交

c++ - QtGridLayout 表现得像 QVBoxLayout?

c++ - 如何避免 C++ 中的多线程问题(wxWidgets 和 Cplex)?

java - 使用 JNI 从 C++ 程序执行 java jar,使用 g++ 或 eclipse

c++ - 奇怪的 std::map 行为

c++ - 为什么 ld 链接器允许使用相同方法定义多个类?

C++ lambda 表达式帮助

c++ - header 和源类文件不起作用