编译错误:未解决的重载函数类型

Pau*_*per 4 c++ templates compilation member-pointers

我尝试使用g ++ 4.7.2编译以下内容:

template <typename T>
struct A {
    struct B {
        T t;

        template<T B::*M>
        T get() {
            return this->*M;
        }
    };

    B b;

    T get() {
        return b.get<&B::t>();
    }
};


int main() {
    A<int> a;
    a.get();
}
Run Code Online (Sandbox Code Playgroud)

它给了我

test.cpp: In member function ‘T A<T>::get()’:
test.cpp:15:23: error: expected primary-expression before ‘)’ token
test.cpp: In instantiation of ‘T A<T>::get() [with T = int]’:
test.cpp:22:8:   required from here
test.cpp:15:23: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int A<int>::B::*’ to binary ‘operator<’
Run Code Online (Sandbox Code Playgroud)

为什么?

谢谢.

And*_*owl 9

您需要使用template消歧器:

return b.template get<&B::t>();
Run Code Online (Sandbox Code Playgroud)

没有它,在解析表达式时:

b.get<&B::t>();
Run Code Online (Sandbox Code Playgroud)

编译器无法判断它是否应该解释get为成员变量的名称后跟<符号(小于),或者作为成员函数模板的实例化get.

虽然我们知道表达式的意图是什么,但编译器不能,至少在实例化之前不会发生 - 并且即使您的函数从未实例化,也会执行语法分析.

  • @PaulDraper:实际上,我发现[这个问答](http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords)这应该很好地解释. (2认同)