How do I pass a function as parameter?

后端 未结 3 1408
时光说笑
时光说笑 2020-12-21 22:22

What is the fastest and shortest way to pass a function as parameter of another function without using other libraries other than the std one in just one line?

I mea

相关标签:
3条回答
  • 2020-12-21 23:21

    Try "pointers to member functions" if your function is a member of any class.

    0 讨论(0)
  • 2020-12-21 23:21

    You are looking at several options.

    1. function pointers, the C style way
    2. std::function which is part of C++ TR1 and C++11
    3. use functors and std::ptr_fun to adapt your function

    The syntax you are showing is only going to work with C++11. Earlier C++ versions don't offer the possibility to define an anonymous function.

    0 讨论(0)
  • 2020-12-21 23:24

    C++11 provides anonymous functions:

    forloop(3, []{ std::cout "Hi!"; });
    

    Example:

    #include <iostream>
    #include <functional>
    
     void forloop(int times, std::function<void()> f) {
         for(int i = 0; i < times; i++) {
             f();
         }
     }
    
    int main() {
        forloop(3, [] () { std::cout << "Hello world"; });
    }
    
    0 讨论(0)
提交回复
热议问题