作为后续能否TR1 ::功能燕子返回值? ,怎么能一个变通的限制tr1::function
无法下咽的返回值?
这应该吞咽采取任何参数的可调用对象的返回值的特定情况下工作:
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);
我假设可变参数模板和完善的转发将允许该技术将任意参数列表的推广。 有没有更好的办法?
在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');
}
下面是一个使用lambda表达式的包装,但它不是AUTOMAGIC还
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
的类型擦除,这是很难得的基本类型。 不过,如果你直接去的函数引用,就可以避免这些问题完全:
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();
}