Aabesh Karmacharya
Aabesh Karmacharya

Reputation: 768

How to define function inside the argument of a function that takes function as argument

#include <iostream>
void print(void func(int)){
  func(6);
}
int main(){
  print(void ext(int r){
  std::cout<<r;
  });
  return 0;
}

i want to define a function inside the parameter itself instead of defining it somewhere else and using its name as parameter. Like in javascripts.

Upvotes: 2

Views: 1183

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409166

This is very easy with two new new features in C++11: std::function and lambda expressions:

void print(std::function<void(int)> func)
{
    func(6);
}

int main()
{
    print([](int r){ std::cout << r; });
}

With std::function you can use any callable object, not only lambda expressions.

For example:

// The `print` function as above

void print_num(int r)
{
    std::cout << r;
}

int main()
{
    print(print_num);
}

Or

// The `print` function as above

struct printer
{
    void operator()(int r)
    {
        std::cout << r;
    }
};

int main()
{
    print(printer());  // Creates a temporary object
}

Upvotes: 3

Mike Seymour
Mike Seymour

Reputation: 254451

In C++11 or later, you can do that with a lambda:

print([](int r){std::cout << r;});

Since print takes a plain function pointer, you're restricted to simple stateless lambdas like this one; you can't capture anything. You might like to give it more flexibility through polymorphism, either using a template:

template <typename Function>
void print(Function func) {
    func(6);
}

or type erasure:

void print(std::function<void(int)> func) {
    func(6);
}

Upvotes: 5

Related Questions