如何在 Boost.MPL 中使用嵌套元函数
How to use nested metafunctions in Boost.MPL?
>我有一个简单的元函数:
template <typename T>
using is_const_lvalue_reference = mpl::and_<
std::is_lvalue_reference<T>,
std::is_const<typename std::remove_reference<T>::type>
>;
显然,如果T
是 MPL 占位符,则它不起作用,因为remove_reference
是针对占位符类而不是替换类型进行评估的。如何正确执行此操作才能在 MPL 算法中使用此元函数?
更新:建议的解决方案是用结构替换别名,这将延迟模板实例化std::remove_reference
。问题是,如何在不使用任何帮助程序结构的情况下延迟内联实例化?
template <typename Sequence>
using are_const_lvalue_references = mpl::fold<
Sequence,
mpl::true_,
mpl::and_<
mpl::_1,
mpl::and_<
std::is_lvalue_reference<mpl::_2>,
std::is_const<typename std::remove_reference<mpl::_2>::type>
>
>
>;
由于同样的原因,此示例显然会失败。我应该更改什么才能使其正确?
以这种方式将类型特征编写为别名是行不通的,因为它们会立即实例化。 is_const_lvalue_reference<_1>
完全mpl::and_<std::is_lvalue_reference<_1>, std::is_const<_1>>
(因为_1
不是引用类型) - 这总是false
,因为左值引用不是const
。不过写false_
非常棘手的方法!
相反,您必须延迟实例化。只需使类型特征继承自mpl::and_
而不是为其别名:
template <class T>
struct is_const_lvalue_reference
: mpl::and_<
std::is_lvalue_reference<T>,
std::is_const<std::remove_reference_t<T>>
>
{ };
这样,除非我们实际尝试访问is_const_lvalue_reference<T>::type
,否则std::remove_reference_t<T>
不会被实例化 - 直到_1
被替换为 apply
中的真实类型才会发生这种情况。
或者,由于apply<>
将在查找占位符的位置调用::type
,因此您可以自己删除::type
的显式调用。所以这有效:
BOOST_MPL_ASSERT(( mpl::apply<
std::is_const<std::remove_reference<_1>>,
int const&
> ));
或原始表达式:
BOOST_MPL_ASSERT(( mpl::apply<
mpl::and_<
std::is_lvalue_reference<_1>,
std::is_const<std::remove_reference<_1>>
>,
int const&
> ));
请注意,此构造不能用作类型特征。
相关文章:
- 通过两个嵌套函数传递C++函数的名称
- 使用嵌套函数数组是个好主意吗?
- C++运行时构建嵌套函数
- C++ 中深度嵌套函数的单个捕获全部语句?
- 不能做嵌套函数,有什么办法呢?
- LLVM - 如何使嵌套函数看到外部函数的变量
- 为什么链表中的数据在嵌套函数中会更改/损坏?
- 为什么编译器会在二进制中留下嵌套函数的实现
- Switch语句-嵌套函数-C++
- 在C++中,是否存在将结束父函数的嵌套函数的返回
- 在c++线程中嵌套函数调用
- 嵌套函数或方法调用会降低应用程序的性能
- C++中嵌套函数声明的范围
- 使用lambda执行嵌套函数
- 如何在C++的嵌套函数中使用指针
- (C++) 使用 lambda 作为嵌套函数,甚至用作通用函数
- 退出嵌套函数中的线程
- 在我的解释器中绑定嵌套函数的更好方法
- 临时对象的生命周期:嵌套函数调用中指向临时向量的迭代器
- c++中的嵌套函数