5

我尝试使用 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();
}

它给了我

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 ‘&lt;unresolved overloaded function type>’ and ‘int A<int>::B::*’ to binary ‘operator<’

为什么?

谢谢。

4

1 回答 1

13

您需要使用template消歧器:

return b.template get<&B::t>();

没有它,解析表达式时:

b.get<&B::t>();

编译器无法判断它是否应该解释get为成员变量的名称后跟一个<符号(小于),或者解释为名为get.

尽管我们知道我们的表达式的预期含义是什么,但编译器不能,至少在实例化发生之前不能 - 并且即使您的函数从未实例化,也会执行句法解析。

于 2013-03-28T23:17:14.607 回答