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)
为什么?
谢谢.
您需要使用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.
虽然我们知道表达式的意图是什么,但编译器不能,至少在实例化之前不会发生 - 并且即使您的函数从未实例化,也会执行语法分析.