The following code:
struct A
{
int f(int);
auto g(int x) -> decltype(f(x));
};
Fails to compile with the error:
error: cannot call member function 'int B::f(int)' without object
If I change it to:
struct A
{
int f(int);
auto g(int x) -> decltype(this->f(x));
};
I get another error:
error: invalid use of 'this' at top level
What is wrong with either of these? I am using gcc 4.6
decltype(auto) is primarily useful for deducing the return type of forwarding functions and similar wrappers, where you want the type to exactly “track” some expression you're invoking.
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 )
Here are the magic words:
struct A
{
int f(int);
auto g(int x) -> decltype((((A*)0) ->* &A::f)(x)) ;
};
Edit I see from Mikael Persson's answer that this is how it's done in boost.
result_of and decltype in combination can give the the return type for a member function
#include <type_traits>
using namespace std;
struct A
{
int f(int i) { return i; }
auto g(int x) -> std::result_of<decltype(&A::f)(A, int)>::type
{
return x;
}
};
int main() {
A a;
static_assert(std::is_same<decltype(a.f(123)),
decltype(a.g(123))>::value,
"should be identical");
return 0;
}
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