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

标签 c++ c++11 c++98

假设我有一个函数:

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++ - 如何在 C++11/98 中使用 <functional> 跳过参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31442984/

相关文章:

c++ 11以下lambda函数的作用域是什么

c++求和使用for循环和二维数组

C++初学者算法作业

c++ - 用 C++11 编译比用 C++98 慢吗?

c++ - 使用 boost::variant 遍历树节点的模板

c++ - win32 std::thread 是否泄漏内存?

C++,Linux : how to limit function access to file system?

C++11 移动和重新分配

c++ - 是否可以将文字值传递给 C++ 中的 lambda 一元谓词?

c++ - 指向抽象类的指针的函数重载