Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 700
Silversonic Avatar asked Oct 13 '15 22:10

Silversonic


People also ask

What is decltype function?

The decltype type specifier yields the type of a specified expression. The decltype type specifier, together with the auto keyword, is useful primarily to developers who write template libraries. Use auto and decltype to declare a function template whose return type depends on the types of its template arguments.

What does decltype stand for?

Decltype keyword in C++ Decltype stands for declared type of an entity or the type of an expression. It lets you extract the type from the variable so decltype is sort of an operator that evaluates the type of passed expression. SYNTAX : decltype( expression )

Is decltype runtime or compile time?

decltype is a compile time evaluation (like sizeof ), and so can only use the static type.


1 Answers

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>.

like image 65
Shoe Avatar answered Sep 24 '22 00:09

Shoe