The root cause of the problem seems to be the internal copying of its arguments performed by std::bind
, with particular reference to t
.
You may want to workaround it this way:
template <typename T>
explicit X(T t)
{
std::bind(&X::invoke<T>, this, std::placeholders::_1)(t);
// ^^^^^^^^^^^^^^^^^^^^^ ^
}
This will also work, but you won't be allowed to make the result of bind
outlive the argument t
(otherwise, you would be passing a dangling reference to invoke<T>()
):
template <typename T>
explicit X(T t)
{
std::bind(&X::invoke<T>, this, cref(t))();
// ^^^^^^^
}
UPDATE:
The above solutions are workarounds that help for achieving what you are showing in your example. However, it emerged from the comments that your use case may be quite different (e.g. passing around the result of bind
for later evaluation).
As correctly pointed out by Maxim Yegorushkin in his answer, the conceptually correct solution consists in using a construct such as Boost's protect
.
In case you do not want to use Boost, it is quite easy to define your own protect()
function using C++11's variadic templates:
// Imitates boost::protect, but with variadic templates and perfect forwarding
namespace detail
{
template<typename F>
struct protect
{
private:
F _f;
public:
explicit protect(F f): _f(f)
{
}
template<typename... Ts>
auto operator () (Ts&&... args) ->
decltype(_f(std::forward<Ts>(args)...))
{
return _f(std::forward<Ts>(args)...);
}
};
}
template<typename F>
detail::protect<F> protect(F&& f)
{
return detail::protect<F>(std::forward<F>(f));
}
Eventually, this is how you could use it in your class, as Maxim suggested:
class X
{
public:
template <typename T>
explicit X(T t)
{
auto pt = protect(t);
std::bind(&X::invoke<decltype(pt)>, this, pt)();
}
private:
template <typename T>
void invoke(T t)
{
t();
}
};