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() {}
This produces
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()
the difference being that the definition has (A<T>*)0
where the declaration has (A<T>*)this
. What gives?
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.
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);
Into:
T x;
decltype(std::declval<T>().foo) f();
std::declval is very useful here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With