在声明后对成员函数定义使用decltype

Using decltype with member function definitions after declaration

本文关键字:定义 decltype 函数 成员 声明      更新时间:2023-10-16

我使用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() {}

这会产生

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()

不同之处在于定义具有CCD_ 1,其中声明具有(A<T>*)this。什么东西?

这是我在这里报告的gcc 4.7中的一个错误:错误#54359(请参阅错误报告的底部)。gcc 4.6接受了这种特殊情况。

作为一种变通方法,不要使用尾随返回类型,而是直接使用成员x的类型。在本例中,这只是T,但您也可以转换更复杂的情况。例如,您可以转换:

T x;
auto f() -> decltype(x.foo);

进入:

T x;
decltype(std::declval<T>().foo) f();

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