通过参数接收到的对象的功能指针
Function pointer on object received by parameter
i具有接收对象实例和功能指针的函数。如何在对象实例上执行我的功能指针?
我尝试过:
void Myclass::my_fn(Object obj, bool (*fn)(std::string str))
{
obj.fn("test"); // and (obj.fn("test"))
}
,但没有任何作用。它告诉我"未使用的参数my_fn和fn"
这是因为 fn
不是 Object
的成员函数指针。为此,您必须做例如。
bool (Object::*fn)(std::string)
然后称呼它必须做
(obj.*fn)(...);
但是,如果您的编译器和库可以支持C 11,我建议您使用std::function
和std::bind
:
void MyclasS::my_fn(std::function<bool(std::string)> fn)
{
fn("string");
}
然后将my_fn
函数称为
using namespace std::placeholders; // For `_1` below
Object obj;
myclassobject.my_fn(std::bind(&Object::aFunction, &obj, _1));
使用std::function
,您还可以使用其他功能指针或lambdas:
myclassobject.my_fn([](std::string s){ std::cout << s << 'n'; return true; });
函数指针是完全不同的形式成员函数指针(用于方法的指针)。
在功能指针的情况下,您不需要任何对象来调用它们:
void Myclass::my_fn(bool (*fn)(std::string str))
{
fn("test");
}
如果成员函数指针正确的语法为:
void Myclass::my_fn(Object obj, bool (Object::*fn)(std::string str))
{
obj.*fn("test");
}
相关文章:
- 将带有派生模板的对象传递给接受具有基本模板的对象的功能
- 对象内部对象的重载功能
- 基于不同字段的对象向量的排序功能
- 具有小对象优化功能的智能指针
- 如果在创建对象时创建了 VPTR,那么为什么具有虚拟功能的类的大小在 32 位系统上为 4,在 64 位机器上为 8
- 如何改进我的"String"对象比较功能
- 如何存储指针以功能模板,该模板将可呼叫对象作为其参数之一
- GPU设备函数如何访问主机功能中定义的对象
- 如何将对象用作C 功能的参数
- 如何将指针分配给功能中的新对象,而不会使该对象在退出后消失
- 将对象传递到类,没有接收匹配功能错误
- 是否可以在辅助功能中概括对象类型
- 使用for_each从对象列表中调用打印功能
- 如何创建功能以用受保护或私人侵犯的对象在对象内部操纵对象
- 实现功能对象绑定而无需使用C 11
- 在功能中设置对象变量
- 成员功能在面向对象的框架中返回std :: vector.size()的效率
- 如何使程序使用功能过载用于派生的类对象
- 明智的选择是更喜欢lambdas功能对象
- 在C 中使用DLSYM加载共享对象功能