如何在 <functional> C++11/98 中使用跳过参数
How to skip an argument using <functional> in C++11/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++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);
}
相关文章:
- 在 c++11 中为 pthread 设置调度参数
- 为什么 c++11 std::lock 和 std::scoped_lock 至少需要 2 个参数?
- 在 C++11 中获取函子作为参数
- C++/11 auto 关键字是在更有效时推导参数进行按引用传递,还是始终按值传递?
- 如何捕获函数参数并存储函数指针以供以后在 C++11 中执行?
- C++11:无法推断模板参数
- 带有void类型和参数的C++11模板专用化
- 使用 C++11 将指向成员函数的指针作为参数传递
- 遍历地图并将该对用作参考参数 C++11
- 发生 Qt5.11 应用插件构建错误:信号和插槽参数不兼容
- 将方法作为模板化参数传递 C++11
- C++11:标准::result_of<>模板参数与标准::函数<>
- 如果没有带有函数签名的 rvalue 参数,是否会执行 C++ 11 中的移动语义?
- C++11: 如何编写一个像 Get 一样工作的模板函数<tuple>...但是收到参数包?
- 如何在 C++11 中创建具有命令行参数大小的动态数组?
- C++ 11 个模板,参数包的别名
- 谷物/C++ 11 - 如何指定反序列化的可选参数
- 变量作为 C++11 属性参数
- 具有列表参数C++11/C++14样式的求和函数
- 将 lambda 表达式传递给 lambda 参数 c++11