-
Predicate definition
Does the C++ standard define an interface for a predicate?
The reason I am asking is that I have an template class (see below) where I would like to accept a predicate as an input to the constructor. How do I specify a predicate as an input argument to the constructor? I have read online that the unary_function<> base class in the standard is not intended to be an interface.
Code:
template<typename T>
Class Myfoo
{
Myfoo();
...
}
One example I have seen online somewhere is this;
Code:
template<typename T, typename Pred>
Class Myfoo
{
Myfoo(Pred p);
...
}
but I dont really need another generic type, I want a more specific type, a predicate.
Any suggestions?
-
if you know that all your predicates will have the same signature (parameter count and types), then you can use a typedef like so:
Code:
typedef void Pred(int param1, double param2);
-
There was this effort to standardise concepts that I believe started from the Boost.ConceptCheck library, but it has been delayed to some future edition of the standard.
Anyway, the normal course of things is to do something like your second code snippet, then just use the predicate and let an error happen if it does not follow the prescribed interface. This way it does not have to matter if the user passes a function pointer or a function object as the predicate.
Alternatively, you could define an abstract base class to serve as the predicate interface, but that may just be an unnecessary limitation (and possible virtual function call overhead).
-
If you only want to use the predicate in the constructor, you can make the constructor a template.
Code:
template<typename T>
class Myfoo
{
public:
template <class Pred>
Myfoo(Pred p);
};