[英]template metaprogramming evaluation
So I have a template class that I would like to accept an std::map where the data type is either a raw pointer or an std::unique_ptr. 所以我有一个模板类,我想接受一个std :: map,其中数据类型是原始指针或std :: unique_ptr。 Then in this class I would like to get the type of the underlying pointer: 然后在这个类中我想得到底层指针的类型:
typedef typename boost::mpl::if_<
boost::is_pointer<typename Container::mapped_type>,
typename Container::mapped_type,
typename Container::mapped_type::element_type*
>::type data_type
However I get the following error when instantiating the class using a map with a raw pointer type: 但是,当使用具有原始指针类型的映射实例化类时,我收到以下错误:
error: 'std::map<int, ValueType*>::mapped_type {aka ValueType*}' is not a class, struct, or union type
It seems to me like it is evaluating typename Container::mapped_type::element_type*
on the raw pointer, I thought that with template metaprogramming it would not evaluate that when the if_ succeeded. 在我看来,它正在评估原始指针上的typename Container::mapped_type::element_type*
,我认为使用模板元编程它不会评估当if_成功时。 Should I be going about this a different way? 我应该采取不同的方式吗?
You need a lazy if
– try boost::mpl::eval_if
instead of boost::mpl::if_
: 你需要一个懒惰的 if
- 尝试boost::mpl::eval_if
而不是boost::mpl::if_
:
#include <boost/type_traits/is_pointer.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
template<typename T>
struct extract_element_type
{
typedef typename T::element_type* type;
};
template<typename Container>
struct foo
{
typedef typename boost::mpl::eval_if<
boost::is_pointer<typename Container::mapped_type>,
boost::mpl::identity<typename Container::mapped_type>,
extract_element_type<typename Container::mapped_type>
>::type data_type;
};
Ie, when in doubt, add an extra layer of indirection. 即,如有疑问,请添加一个额外的间接层。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.