解决方法,允许tr1 :: function接收返回值 [英] Workaround to allow tr1::function to swallow return values
问题描述
作为可以使用tr1 :: function swallow返回值的后续动作 ,如何解决 tr1 :: function
不能接收返回值的限制?
As a follow-up to Can tr1::function swallow return values?, how can one work around the limitation that tr1::function
cannot swallow return values?
没有参数的可调用对象的返回值的具体情况:
This should work in the specific case of swallowing the return value of a callable object taking no arguments:
template<typename FuncT>
struct swallow_return_t
{
explicit swallow_return_t(FuncT i_Func):m_Func(i_Func){}
void operator()(){ m_Func(); }
FuncT m_Func;
};
template<typename FuncT>
swallow_return_t<FuncT>
swallow_return(FuncT f)
{
return swallow_return_t<FuncT>(f);
}
然后使用类似:
int Foo();
std::tr1::function<void()> Bar = swallow_return(Foo);
我假设可变参数模板和完美转发允许将此技术泛化到任意参数列表。有没有更好的方法?
I assume variadic templates and perfect forwarding would permit generalization of this technique to arbitrary parameter lists. Is there a better way?
推荐答案
以下适用于我在GCC 4.6.1:
The following works for me in GCC 4.6.1:
#include <functional>
int foo() { return 5; }
int goo(double, char) { return 5; }
int main()
{
std::function<void()> f = foo;
std::function<void(float, int)> g = goo;
(void)f();
(void)g(1.0f, 'a');
}
这里是一个使用lambdas ,但不是自动的
Here's a wrapper using lambdas, but it's not automagic yet
template <typename T, typename ...Args>
struct strip_return
{
static inline std::function<void(Args...)> make_function(std::function<T(Args...)> f)
{
return [&f](Args... args) -> void { f(args...); };
}
};
int main()
{
auto q = strip_return<int>::make_function(std::bind(foo));
q();
}
忘记中间部分。 OK,因为 std :: function
是类型擦除,很难得到底层类型。然而,如果你直接去函数引用,你可以完全避免这些问题:
Forget the middle part. OK, since std::function
is type-erasing, it's hard to get at the underlying types. However, if you go for the function reference directly, you can avoid these problems entirely:
template <typename T, typename ...Args>
static inline std::function<void(Args...)> make_direct(T (&f)(Args...))
{
return [&f](Args... args) -> void { f(args...); };
}
int main()
{
auto p = make_direct(foo);
q();
}
这篇关于解决方法,允许tr1 :: function接收返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!