Silversonic
Silversonic

Reputation: 1329

Decltype of member functions

class A {
    int f(int x, int j) { return 2;}
    decltype(f)* p;
};

Gives me the error:

error: decltype cannot resolve address of overloaded function

I can't understand why that error is even speaking of overloaded functions. Similarly I thought that maybe I needed to use the scope operator to access the function:

class A {
    int f(int x, int j) { return 2;}
    decltype(A::f)* p;
};

Which still gives me an error but a clearer description:

error: invalid use of non-static member function 'int A::f(int, int)'

Why is it that I'm not allowed to use decltype to find the type of a member function? Alternatively setting the member function to static removes the error in either case.

Upvotes: 17

Views: 12265

Answers (1)

Shoe
Shoe

Reputation: 76240

What you really want is:

struct a {
    int f(int x, int j) { return 2;}
    decltype(&a::f) p;
};

Live demo

Since the f you are referring to is a member function. The deduced type is:

int(a::*)(int, int)

Without the & the compiler is assuming that you are trying to call the function without providing arguments to it. Perhaps Clang's error message is clearer about this:

error: call to non-static member function without an object argument
    decltype(a::f) p;

If you really don't want the pointer type you can later apply std::remove_pointer_t from <type_traits>.

Upvotes: 13

Related Questions