C++0x 已弃用旧的绑定(bind)器,如 bind1st
和 bind2nd
,取而代之的是通用的 std::bind
。 C++0x lambda 与 std::bind
很好地绑定(bind),但它们不与经典的 bind1st 和 bind2nd 绑定(bind),因为默认情况下 lambda 没有嵌套的 typedef,例如 argument_type
、first_argument_type
、second_argument_type
和 result_type
。
所以我认为 std::function
可以作为将 lambda 绑定(bind)到旧绑定(bind)器的标准方法,因为它公开了必要的 typedef。
但是,在这种情况下很难使用 std::function
,因为它会强制您在实例化函数时拼写出函数类型。
auto bound =
std::bind1st(std::function<int (int, int)>([](int i, int j){ return i < j; }), 10); // hard to use
auto bound =
std::bind1st(std::make_function([](int i, int j){ return i < j; }), 10); // nice to have but does not compile.
我无法为 std::function
找到方便的对象生成器。像 std::make_fuction
这样的东西会很好。这样的事情存在吗?如果没有,是否有任何其他更好的方法将 lamda 绑定(bind)到经典绑定(bind)器?
最佳答案
从来没有尝试过这样做,我也没有时间提供完整的答案,但我想 Boost.FunctionTypes 可以做一些事情。
这是一个粗略的、不完整的、未经测试的草稿,可以给你一个想法:
template <typename T>
struct AdaptedAsUnary : T
{
namespace bft = boost::function_types;
namespace bmpl = boost::mpl;
typedef typename bft::result_type<T>::type result_type;
typedef typename bmpl::front<typename bft::parameter_types<T>::type>::type argument_type;
AdaptedAsUnary(T t) : T(t) {}
};
template <typename T>
AdaptedAsUnary<T>
AdaptAsUnary(T t)
{
return AdaptedAsUnary<T>(t);
}
关于c++ - 使用弃用的绑定(bind)器和 C++0x lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2594114/