将函数对象作为函数参数传递
Passing a function object as function argument
我想以多种方式将我的初始函数对象传递给我自己的函数。
我没有找到任何具有" for_each"功能的示例,但据我所知,它应该以相同的方式工作。
void f(int& n, void (*g)(int& m) ){ g(n);};
class TEST{
public:
int init=0;
TEST(int _init):init(_init){}
void operator() (int& m) {m+=init;}
};
int main(int argc, char *argv[])
{
int k, m;
cin >> k >> m;
TEST mytest(m); // OK, creates object with initialization
mytest(m); // OK, using initialized object's "operator()"
f(k,mytest); // error: cannot convert 'TEST' to
// 'void (*)(int&)' for argument '2'to
// 'void f(int&, void (*)(int&))'
f(k,TEST(m)); // error: cannot convert 'TEST' to
// 'void (*)(int&)' for argument '2'to
// 'void f(int&, void (*)(int&))'
return 0;
}
类型void (*)(int& m)
的函数指针与TEST
的实例?
它们可召唤, int&
类型。
有什么区别?
它们是两种不同的类型。除非您使用函数模板,否则不能互换使用它们。
因此,解决方案是使用函数模板。
template <typename Callable>
void f(int& n, Callable c )
{
c(n);
}
相关文章:
- 如何在C++中将迭代器作为函数参数传递
- 为什么我不能将引用作为 std::async 的函数参数传递
- 节点插件 API 将数组作为函数参数传递
- 将字符串数组作为函数参数传递
- 如何通过 C++ 中的函数参数传递初始值设定项列表的固定大小的初始值设定项列表?
- 我可以动态创建新地图并作为函数参数传递吗?
- 将任意模板向量作为函数参数C++传递
- 将函数指针作为函数参数传递的目的
- C++:通过函数参数传递的值给出不同的结果
- 当数组大小在C++中未知时,如何在运行时将对字符串数组的引用作为函数参数传递?
- 通过宏将函数参数传递给函数
- C++:访问作为函数参数传递的双指针数组所指向的变量的值
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 将派生类构造函数参数传递给受保护的成员
- 将指向数组的指针作为函数参数传递,这本身就是另一个函数的返回值?
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 有什么理由C++ 11+ std::mutex 应该声明为全局变量,而不是作为函数参数传递到 std::thread 中
- 如何将派生类作为函数参数传递:如果派生类成员不在父类中怎么办
- 如何将变量作为构造函数参数或函数参数传递
- 当数组对象以函数参数传递时,为什么复制构造函数会自称