C++ Boost函数合成
假设我想要一个函数C++ Boost函数合成,c++,boost,boost-function,function-composition,C++,Boost,Boost Function,Function Composition,假设我想要一个函数double adapter(double),有没有一种通用的方法可以将它与boost::function functor组合,生成另一个boost::function functor 2,其中functor 2(…)==适配器(functor(…)?特别是,如果有一种不用C++11就能做到这一点的方法,那就太酷了 编辑为了澄清,我想知道是否有一种方法可以编写能够处理任何boost::function的函数,即具有不同长度签名的函数,而不必为1、2、3等参数多次复制和粘贴。没有
double adapter(double)
,有没有一种通用的方法可以将它与boost::function functor
组合,生成另一个boost::function functor 2
,其中functor 2(…)==适配器(functor(…)
?特别是,如果有一种不用C++11就能做到这一点的方法,那就太酷了
编辑为了澄清,我想知道是否有一种方法可以编写能够处理任何
boost::function
的函数,即具有不同长度签名的函数,而不必为1、2、3等参数多次复制和粘贴。没有c++11,存在大量的复杂性,包括varadic参数和转发
使用C++11,它可以实现,主要是通过专门化std::is\u bind\u表达式来实现。在绑定中使用此函数对象时,它将调用存储在绑定函数对象调用期间提供的所有参数中的函数对象。注意,这适用于任何函数对象,而不仅仅是std::function
这适用于GCC4.7
#include <functional>
#include <utility>
#include <type_traits>
namespace detail
{
template<typename Func>
struct compose_functor
{
Func f;
explicit compose_functor(const Func& f) : f(f) {};
template<typename... Args>
auto operator()(Args&&... args) const -> decltype(f(std::forward<Args>(args)...))
{
return f(std::forward<Args>(args)...);
}
};
}
template<typename Func>
detail::compose_functor
<Func> compose(Func f)
{
return detail::compose_functor<Func>(f);
}
namespace std
{
template<typename T>
struct is_bind_expression< detail::compose_functor<T> > : true_type {};
}
#include <numeric>
int adapter(double d)
{
return (int)d;
}
int main()
{
std::function<int(double)> f1 = std::bind(adapter, compose(std::negate<double>()));
std::function<int(double, double)> f2 = std::bind(adapter, compose(std::plus<double>()));
// 1.5 -> -1.5 -> -1
std::cout << f1(1.5) << std::endl;
// 2.3+4.5 = 6.8 -> 6
std::cout << f2(2.3, 4.5) << std::endl;
}
#包括
#包括
#包括
名称空间详细信息
{
模板
结构复合函数
{
函数f;
显式复合函子(const-Func&f):f(f){};
模板
自动运算符()
{
返回f(标准::转发(参数)…);
}
};
}
模板
detail::compose_函子
组合(函数f)
{
返回细节::compose_函子(f);
}
名称空间标准
{
模板
结构是绑定表达式:true\u type{};
}
#包括
int适配器(双d)
{
返回(int)d;
}
int main()
{
std::function f1=std::bind(适配器,组合(std::negate());
std::function f2=std::bind(适配器,组合(std::plus());
// 1.5 -> -1.5 -> -1
在C++03中,cout支持不同数量的参数并不是一件轻而易举的事。