C++ 如何循环非默认构造类的boostmpl列表?
我举了以下例子:C++ 如何循环非默认构造类的boostmpl列表?,c++,boost,boost-mpl,C++,Boost,Boost Mpl,我举了以下例子: #包括 #包括 #包括 结构一{}; 结构二{}; 结构三{}; 结构四{}; 结构五{five()=delete;}; 模板 作废打印() { 你可以自己做一些事情,比如: namespace detail { template <typename Tuple> structure my_for_each_t; template <typename... Ts> structure my_for_each_t<
#包括
#包括
#包括
结构一{};
结构二{};
结构三{};
结构四{};
结构五{five()=delete;};
模板
作废打印()
{
你可以自己做一些事情,比如:
namespace detail {
template <typename Tuple>
structure my_for_each_t;
template <typename... Ts>
structure my_for_each_t<boost::mpl::list<Ts...>>
{
template <typename F>
void operator()(F f) const
{
initializer_list<int>{(static_cast<void>(f<Ts>()), 0)...};
}
};
}
template <typename Tuple, typename F>
void my_for_each(F f)
{
detail::my_for_each_t<Tuple>()(f);
}
您还可以向类型列表中的项目添加一级间接寻址,如下所示:
template <typename T>
struct type_ref
{
typedef T type;
}
struct type_printer
{
template <typename T>
void operator()(T)
{
print<T>();
}
template <typename T>
void operator()(type_ref<T>)
{
print<T>();
}
};
int main()
{
typedef boost::mpl::list<
one,
two,
three,
four,
type_ref<five>
>::type type_list;
boost::mpl::for_each<type_list>(type_printer());
}
模板
结构类型_ref
{
T型;
}
结构式打印机
{
模板
void运算符()(T)
{
打印();
}
模板
void运算符()
{
打印();
}
};
int main()
{
typedef boost::mpl::list<
一,,
二,,
三,,
四,,
参考类型
>::类型列表;
boost::mpl::for_each(键入_printer());
}
我通过添加一个类型包装结构解决了这个问题,如Boost.Hana中所示。我将此添加到了一个伟大的想法中,即使用Boost::mpl::transform
将此包装类型自动添加到列表中的每个项目中
以下详细说明了我的解决方案:
模板
结构类型_
{
使用类型=T;
};
模板
结构添加类型包装器
{
使用类型=类型;
};
使用这两种新类型,我将type\u打印机
函子更改为:
struct type\u打印机
{
模板
void运算符()(T)
{
使用type\u t=typename t::type;
打印();
}
};
现在,boost::mpl::for_每个
主调用如下所示:
template <typename T>
struct type_ref
{
typedef T type;
}
struct type_printer
{
template <typename T>
void operator()(T)
{
print<T>();
}
template <typename T>
void operator()(type_ref<T>)
{
print<T>();
}
};
int main()
{
typedef boost::mpl::list<
one,
two,
three,
four,
type_ref<five>
>::type type_list;
boost::mpl::for_each<type_list>(type_printer());
}
使用boost::mpl::_1;
使用wrapped_list=boost::mpl::transform::type;
boost::mpl::for_each(键入_printer());
感谢大家的帮助,我认为这是一个非常好且优雅的解决方案。谢谢,这个答案启发了我,同时也给了我这样的评论:使用boost::mpl::transform
自动包装列表中的所有对象。
template <typename T>
struct type_ref
{
typedef T type;
}
struct type_printer
{
template <typename T>
void operator()(T)
{
print<T>();
}
template <typename T>
void operator()(type_ref<T>)
{
print<T>();
}
};
int main()
{
typedef boost::mpl::list<
one,
two,
three,
four,
type_ref<five>
>::type type_list;
boost::mpl::for_each<type_list>(type_printer());
}