Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using decltype with member function definitions after declaration

Tags:

c++

c++11

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?

like image 368
Bakkot Avatar asked Feb 20 '23 04:02

Bakkot


1 Answers

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.

like image 66
Bruno De Fraine Avatar answered May 01 '23 23:05

Bruno De Fraine