从 MPL 元函数类创建函子
我一直在 MPL 中寻找一个类,它将从行为良好的 MPL 元函数类创建函数对象。我手工完成了这个实现:
template <class Lambda, class Result>
struct functor
{
typedef Result result_type;
template <typename Type>
Result operator()( Type )
{ return Lambda::template apply<Result>::type::value; }
};
一个使用示例是
Foo foo;
return functor< boost::mpl::always<boost::mpl::int_<5> >, int >( foo );
编写 return 5
的美化版本。
由于这个操作看起来非常基本,我原以为 MPL 中已经有一个类似的类,但搜索文档并没有给我带来任何结果。我错过了什么吗?
I've been looking for a class in MPL that will create a function object from a sufficiently well-behaved MPL metafunction class. I hand-rolled this implementation:
template <class Lambda, class Result>
struct functor
{
typedef Result result_type;
template <typename Type>
Result operator()( Type )
{ return Lambda::template apply<Result>::type::value; }
};
A usage example would be
Foo foo;
return functor< boost::mpl::always<boost::mpl::int_<5> >, int >( foo );
as a glorified version of writing return 5
.
As this operation seems pretty basic, I'd have thought there is already a similar class in MPL, but a search of the documentation didn't yield anything for me. Am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为 Boost.MPL 中没有这样的类,因为它们只专注于编译时计算。这种包装器宁愿保存在 Boost 中。 Fusion,旨在建立编译和运行时实体之间的链接,但我没有找到任何东西。
我认为您必须使用自己的实现,乍一看似乎没问题(尽管我宁愿使用
mpl::apply
来处理占位符表达式)。我认为您也可以省略返回类型,因为它可以从 lambda 推导出来。下面是使用
apply
并从 lambda 推导返回类型的替代实现:I don't think there is such a class in Boost.MPL, since they focus exclusively on compile-time computations. This kind of wrapper would rather be held in Boost.Fusion, which aims at making the link between compile and runtime entities, but I did not found anything.
I think you will have to use your own implementation, which seems alright at a glance (even though I would rather use
mpl::apply
to handle placeholder expressions). I think you could also omit the return type, since it can be deduced from the lambda.Here is an alternate implementation using
apply
and deducing the return type from the lambda: