繁体   English   中英

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

[英]Using decltype with member function definitions after declaration

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

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

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

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

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

成:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM