I have a problem when calling nested expressions std::bind. The following code demonstrates the problem. It does not compile with libC ++, but works with boost:
#define BOOST 0
#if BOOST
#include <boost/function.hpp>
#include <boost/bind.hpp>
using boost::function;
using boost::bind;
#else
#include <functional>
using std::function;
using std::bind;
using std::placeholders::_1;
#endif
int sum(int a, int b) { return a+b; }
template <typename F>
int yeah(F f, int c)
{
return f(c);
}
template <typename F>
int nope(F f, int c)
{
return bind(f, c)();
}
template <typename F>
int fix1(F f, int c)
{
function<int(int)> g = f;
return bind(g, c)();
}
template <typename F>
class protect_t
{
public:
typedef typename F::result_type result_type;
explicit protect_t(F f): f_(f) {}
template <typename... Args>
result_type operator()(Args&&... args)
{
return f_(std::forward<Args>(args)...);
}
private:
F f_;
};
template <typename F>
protect_t<F> protect(F f)
{
return protect_t<F>(f);
}
template <typename F>
int fix2(F f, int c)
{
return bind(protect(f), c)();
}
#include <iostream>
int main()
{
std::cout << yeah(bind(sum, _1, 4), 5) << std::endl;
std::cout << nope(bind(sum, _1, 4), 5) << std::endl;
std::cout << fix1(bind(sum, _1, 4), 5) << std::endl;
std::cout << fix2(bind(sum, _1, 4), 5) << std::endl;
}
The flow around the binding expression in std::function(see fix1) fixes the problem, although it sacrifices speed because of the rejection of polymorphism at run time (without measuring it).
The flow of the bind expression in protect_t(see fix2) is inspired boost::protect, however, compilation with lib ++ is not performed due to the impossibility of copying bind instances. It makes me wonder why you wrap them all the same std::function.
, ? std::bind? , , ++ 11 (. ), , ?