将一元谓词传递给 C++ 中的函数
我需要一个函数来为我的类建立显示项目的策略。 例如:
SetDisplayPolicy(BOOLEAN_PRED_T f)
假设 BOOLEAN_PRED_T 是指向某些布尔谓词类型的函数指针,例如:
typedef bool (*BOOLEAN_PRED_T) (int);
我只对例如感兴趣:当传递的谓词为 TRUE 时显示某些内容,当它为 false 时不显示。
上面的示例适用于返回 bool 并采用 int 的函数,但我需要一个非常通用的指针作为 SetDisplayPolicy 参数,所以我想到了 UnaryPredicate,但它与 boost 相关。 如何将一元谓词传递给 STL/C++ 中的函数? 一元函数< bool,T >
不起作用,因为我需要一个 bool 作为返回值,但我想以最通用的方法询问用户“返回 bool 的一元函数”。
我想推导我自己的类型:
template<typename T>
class MyOwnPredicate : public std::unary_function<bool, T>{};
这可能是一个好方法吗?
I need a function which establishes a policy for my class for displaying items. e.g:
SetDisplayPolicy(BOOLEAN_PRED_T f)
This is assuming BOOLEAN_PRED_T is a function-pointer to some boolean predicate type like:
typedef bool (*BOOLEAN_PRED_T) (int);
I'm interested only on e.g: display something when the passed predicate is TRUE, do not display when it's false.
The above example works for functions returning bool and taking an int, but I need a very generic pointer for the SetDisplayPolicy argument, so I thought of UnaryPredicate, but it's boost related. How I can pass a unary predicate to a function in STL/C++? unary_function< bool,T >
won't work because I need a bool as return value, but I want to ask the user just for "unary function that returns bool", in the most generic approach.
I thought of deriving my own type as:
template<typename T>
class MyOwnPredicate : public std::unary_function<bool, T>{};
Could that be a good approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
SetDisplayPolicy
转换为函数模板:然后使用,执行:
在显示代码中,您将执行以下操作:
当然,您的函子可能需要有一个状态,并且您可能希望其构造函数执行以下操作重点是 SetDisplayPolicy 并不关心你给它什么(包括函数指针),只要你可以将函数调用粘贴到它上面并返回一个 bool< /代码>。
编辑:并且,正如csj所说,您可以继承STL的
unary_function
,它可以做同样的事情,并且还会为您购买两个typedef
<代码>argument_type 和result_type
。Turn
SetDisplayPolicy
into a function template:Then to use, do:
In the display code you would then d someting like:
Of course, your functor may need to have a state and you may want its constructor to do stuff, etc. The point is that
SetDisplayPolicy
doesn't care what you give it (including a function pointer), provided that you can stick a function call onto it and get back abool
.Edit: And, as csj said, you could inherit from STL's
unary_function
which does the same thing and will also buy you the twotypedef
sargument_type
andresult_type
.