0

is there any possibility to have a lambda expression inside a struct in c++ . logic goes as follows.

struct alpha {
  <lambda function> {
   /* to do */
}

};

int main()
{
int a =   //call the function inside the struct and compute.

}
Coding4Life
  • 619
  • 2
  • 7
  • 14
  • 9
    why you need a lambda function and not a normal member function? Please, elaborate your use case, since this seems to be an XY problem – LoPiTaL Sep 14 '19 at 15:27
  • 3
    Of course it's possible! It's called a "class method". It effectively captures `this`, plus whatever parameters you pass into it. See your C++ book for more details. – Sam Varshavchik Sep 14 '19 at 15:27

3 Answers3

2

You'll need to use std::function:

#include <iostream>
#include <functional>

struct Foo
{
    const std::function<void()> hello = [] () { std::cout << "hello world!" << std::endl; };
};

int main()
{
    Foo foo {};
    foo.hello();
}

See live on Coliru.

Daniel
  • 8,179
  • 6
  • 31
  • 56
1

It's unclear what you're asking exactly.
But a lambda, a.k.a. a functor, in C++ is mainly syntactic sugar for operator().
If you want to have a "callable" struct, you can just define operator() like this:

struct alpha {
    int operator() () {
        return 42;
    }
};

int main()
{
    alpha x;
    int a = x();
    std::cout << a << std::endl; // prints "42"

}
rustyx
  • 80,671
  • 25
  • 200
  • 267
-1

Yes, you can use std :: function to declare a pointer to a function, and when initializing the structure, substitute a function with the lambda pointer, for example struct alpha{ std::function<int(int)> }; ... alpha a{[](int a){return a;}};

Silerus
  • 36
  • 6