Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ alternative member definition

In C++ you can define members the following way:

struct test {
    using memberType = int(int);
    /*virtual*/ memberType member;
};

int test::member(int x) { return x; }

With C++14 is there any way to define the member inside the class definition, for instance with a lambda ?

like image 917
Gaetano Avatar asked Jun 14 '16 10:06

Gaetano


2 Answers

I don't think that's possible, but you could do it if the member is a pointer to function

struct test {
    int (*member)(int) = [](int x){return x;};
};

since a lambda with an empty capture list is actually a regular function

like image 123
gbehar Avatar answered Sep 19 '22 00:09

gbehar


The only way I could think of us to use a std::function<> object, but you have to pass the instance (can't think of how it could be automatically bound..)

struct foo {
    using T = int(foo&, int);

    int b;
    std::function<T> x = [](foo& f, int a) { return a * f.b; };
};
like image 24
Nim Avatar answered Sep 20 '22 00:09

Nim