How to pass a std-functor in c++ and use it without knowing which one it is specifically
I have something like a sort-algorithm here, and I want to pass it a functor, which provides the sorting criteria (std::binary_function). So it should call T.operator<() for example if std::less is given.
Problem is, the member function operator() is not virtual. So I need to know which type of object was given, to perform a dynamic cast which is not really nic开发者_Python百科e.
Regards,
Dennis
Problem is, the member function operator() is not virtual. So I need to know which type of object was given, to perform a dynamic cast which is not really nice.
Why do you want to perform a dynamic cast? Normally you don’t need that. Just call the functor’s operator()
just like you would call a normal function.
The whole point of a functor is that they behave like normal functions and you’re passing a template parameter into your algorithm (aren’t you?) to handle different functor (and function) types.
Of course, this whole thing is predicated on the fact that you are actually passing a template parameter into your function. std::binary_function
is not suited as a virtual base class. It merely exists to define a few handy typedefs. Thus, your function declaration should look like this:
template <typename TBinaryFunction>
void your_algorithm(rest of parameters …, TBinaryFunction f);
Can't you pass your functor as a template parameter, so to have static polymorphism?
You can use Qt Signal and Slots or you can use Boost.Function
精彩评论