1. 程式人生 > >C++傳入任意的函式型別作為引數

C++傳入任意的函式型別作為引數

C++程式設計中,有些時候需要傳入函式作為引數,這在STL中作為謂詞經常用到。傳入的可以是函式、函式物件和lambda表示式。程式設計的時候,把它當成一個模板型別傳入即可。以下給出一個簡單的例子:

#include <iostream>
#include <utility>
#include <functional>

template<typename F>
void foo(F f) {
    auto&& res = f();
    std::cout << res << std::
endl; } int f1(int n) { return 2 * n; } bool f2() { return 0.1; } struct Obj { int operator()(int a, int b) { return a + b; } }; int main() { foo(std::bind(&f1, 10)); // 一元引數 foo(std::bind(&f2)); // 無引數函式 int x = 10; foo([&]() { return x; }); // lambda表示式
Obj obj; foo(std::bind(obj, 1, 2)); // 函式物件 return 0; }