Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member function call in decltype

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

like image 996
HighCommander4 Avatar asked Feb 28 '11 20:02

HighCommander4


People also ask

What does decltype auto do?

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.

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 )


2 Answers

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.

like image 134
TonyK Avatar answered Sep 18 '22 05:09

TonyK


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;
}
like image 27
Kjell Hedström Avatar answered Sep 19 '22 05:09

Kjell Hedström