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.
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.
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 )
decltype is a compile time evaluation (like sizeof ), and so can only use the static type.
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>
.
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