如何在 <functional> C++11/98 中使用跳过参数

How to skip an argument using <functional> in C++11/98

本文关键字:参数 C++11 lt functional gt      更新时间:2023-10-16

假设我有一个函数:

void function() {
    cout << "Hello!" << endl;
}

我有一个算法,它调用一个函数并传递两个参数

template <class F>
void my_algorithm(F f) {
    // ...
    f(x, y);
    // ...
}

如何通过操作函数或函数对象将function传递给my_algorithm,而无需手动创建包装器?作为参考,我不想创建的包装器看起来像这样:

void functionSkipArgs(A a, B b) {
    function();
}

换句话说,我想在以下代码中找到与some_operations对应的函数或函数系列:

my_algorithm(some_operations(&function));

这似乎可以工作:http://ideone.com/6DgbA6

#include <iostream>
#include <functional>
using namespace std;

void func() {
    cout << "Hello!" << endl;
}
template<class F>
void my_algorithm(F f) {
    int x = 100;
    int y = 200;
    f(x, y);
}

int main() {
    my_algorithm(std::bind(func));
    return 0;
}

在你的问题被标记的c++11中,使用lambda。下面是代码:

my_algorithm([](A, B) 
{ 
    return function();
});

lambda为你做的是为你的。

如果你想要泛型的(模板化的)并且你有c++14,那么你可以使用auto:

my_algorithm([](auto, auto) 
{ 
    return function();
});

使用std::function和lambda的解:

#include <iostream>
#include<functional>
void function() {
    std::cout << "Hello!" << std::endl;
}
template <typename F>
void my_algorithm(F f) {    
    int x=0;
    int y=10;
    f(x, y);    
}
int main()
{  
    std::function<void(int,int)> fun= [](int x, int y){  function();};        
    my_algorithm(fun);
}