在声明后使用decltype和成员函数定义 [英] Using decltype with member function definitions after declaration
问题描述
我使用decltype作为成员函数的返回类型,但是定义和声明不匹配。以下是一些代码:
I'm using decltype for the return type of a member function, but the definition and declaration don't match. Here's some code:
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> *)this
。
the difference being that the definition has (A<T>*)0
where the declaration has (A<T>*)this
. What gives?
推荐答案
这是gcc 4.7中的一个错误,我在这里报告: bug#54359 (参见错误报告底部)。这种特殊情况被gcc 4.6接受。
This is a bug in gcc 4.7 that I reported here: bug #54359 (see bottom of the bug report). This particular case is accepted by gcc 4.6.
作为解决方法,不要使用结尾返回类型,而使用成员类型 x
。在示例中,这只是简单的 T
,但你也可以转换更复杂的情况。例如,您可以转换:
As a workaround, don't use a trailing return type and use the type of member x
directly. In the example, this is simply T
, but you can also convert more complex cases. For example, you can convert:
T x;
auto f() -> decltype(x.foo);
进入:
T x;
decltype(std::declval<T>().foo) f();
std :: declval 在这里非常有用。
这篇关于在声明后使用decltype和成员函数定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!