声明后使用带有成员函数定义的decltype

Bak*_*kot 4 c++ c++11

我使用decltype作为成员函数的返回类型,但定义和声明不匹配.这是一些代码:

template<typename T>
struct A {
    T x;
    auto f() -> decltype(x);
};

template<typename T>
auto A<T>::f() -> decltype(x) {
    return this->x;
}

int main() {}
Run Code Online (Sandbox Code Playgroud)

这产生了

test.cc:10:6: error: prototype for 'decltype (((A<T>*)0)->A<T>::x) A<T>::f()' does not match any in class 'A<T>'
test.cc:6:7: error: candidate is: decltype (((A<T>*)this)->A<T>::x) A<T>::f()
Run Code Online (Sandbox Code Playgroud)

不同之处在于定义具有(A<T>*)0声明的位置(A<T>*)this.是什么赋予了?

Bru*_*ine 8

这是我在这里报告的gcc 4.7中的一个错误:bug#54359(参见错误报告的底部).gcc 4.6接受了这个特例.

作为解决方法,请不要使用尾随返回类型并x直接使用成员类型.在示例中,这很简单T,但您也可以转换更复杂的情况.例如,您可以转换:

T x;
auto f() -> decltype(x.foo);
Run Code Online (Sandbox Code Playgroud)

成:

T x;
decltype(std::declval<T>().foo) f();
Run Code Online (Sandbox Code Playgroud)

std :: declval在这里非常有用.