通过std :: function传递成员函数 [英] Passing a member function via std::function

查看:609
本文介绍了通过std :: function传递成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查数据字段是否有效(有效表示不为null且未填充默认值)

I want to check if a data field is valid (valid means being not null and not filled with the default value)

基本上

return (!connector->IsNull(field_id) and connector->Get<type>Default(field_id, default_value))

但是类型可以是许多类型之一(字符串,int64等),因此有5-6种不同功能。我为此创建了一个辅助函数,并且尝试传递相关的GetDefault ...

But "type" can be one of many types (string, int64, etc...) so there are 5-6 different functions. I made a helper function for it and I'm trying to pass in the relevant GetDefault...

template<typename T> bool IsValidField(std::unique_ptr<Connector>& connector, const std::function<T(int, T)> &GetDefault, int field_id, T default_value){
  return (!connector->IsNull(field_id) && connection->GetDefault(field_id, default_value) != default_value);
}

然后我用...来调用辅助函数。

And I'm calling the helper function with....

IsValidField(connector, connector->GetStringWithDefault,20,"")

我得到错误错误:对非静态成员函数的引用必须称为
,因为GetStringWithDefault不是静态函数,我该如何解决?

I get the error "error: reference to non-static member function must be called " because GetStringWithDefault isnt a static function, how do I fix this?

或者,有没有办法使它显得不太尴尬?

Alternately, is there a way of making it slightly less awkward?

推荐答案

也许不是最整洁的,但是最简单的解决方案似乎是将所有内容包装到lambda中:

Perhaps not the most neat, but the most trivial solution seems to be to wrap everything into lambda:

IsValidField(connector,[connector ]()-> T {return connector-> GetStringWithDefault(20,)})

但是您需要进行调整 IsValidField 签名相应。

But then you need to adjust the IsValidField signature accordingly.

这篇关于通过std :: function传递成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆