I try to implement a functor version of static_cast for use in std::bind().
I am aware of Boost ll_static_cast<K>() (see using static_cast with boost::bind), but I am not using Boost right now.
There is a code example in Why do several of the standard operators not have standard functors? but it won't compile on GCC 4.2.1:
template <typename Target>
struct StaticCast
{
template <typename Source>
Target operator()(Source&& source) const
{
return static_cast<Target>(source);
}
}
I managed to get something to compile, but I am not sure it's correct:
template <class Target>
struct StaticCast : public std::unary_function<void, Target> {
template <class Source>
Target operator()(Source& src) const {
return static_cast<Target>(src);
}
};
Can someone tell me if this version is correct, and if this is the case, why I need std::unary_function which is not used in the previous code example?
Usage:
std::vector<BaseObject*> vec; // BaseObject* are known to be of type
// DerivedObject* of course, please don't ask me how or why...
std::for_each(vec.begin(), vec.end(),
std::bind(&DerivedObject::doStuff,
std::bind(StaticCast<DerivedObject*>(), std::placeholders::_1),
"with some string"));
Given the lack of perfect forwarding in C++03, you'll have to make due with overloads:
Note that I'm explicitly making a
typedefforresult_typerather than inheriting fromstd::unary_function<>. The reason is that the first template parameter tostd::unary_function<>is supposed to beoperator()'s argument type, but because ouroperator()is a template we can't know this in advance, so it's disingenuous to supply one in the first place (especiallyvoid, which would imply thatoperator()is nullary, when in fact it is unary).Also, for completeness' sake, here is the correct C++11 version of the functor: