Coding4Life
Coding4Life

Reputation: 639

How to define a lambda function inside a struct in c++

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.

}

Upvotes: 0

Views: 5064

Answers (3)

rustyx
rustyx

Reputation: 85382

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"

}

Upvotes: 1

Silerus
Silerus

Reputation: 36

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;}};

Upvotes: -1

Daniel
Daniel

Reputation: 8441

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.

Upvotes: 3

Related Questions