gpt4 book ai didi

c++ - 允许 tr1::function 吞下返回值的解决方法

转载 作者:太空宇宙 更新时间:2023-11-04 14:22:09 25 4
gpt4 key购买 nike

作为 Can tr1::function swallow return values? 的后续行动,如何解决 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 的包装器,但它还不是自动的

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();
}

忘记中间部分。好的,因为 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();
}

关于c++ - 允许 tr1::function 吞下返回值的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6653531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com