我有一个需要 boost::variant 的类,其中包含指向各种类型的共享指针,如下所示:
template <typename ToySharedPtrVariant, typename ColorSharedPtrVariant>
class ToyPicker {
typedef std::pair<
ToySharedPtrVariant,
ColorSharedPtrVariant
> toyAndColorPair;
typedef std::map<
std::string,
std::vector<
toyAndColoPair
>
> stringToToyColorPairMap;
// ... methods that use the defined types...
}
该类目前需要以下形式的模板参数来编译:
ToyPicker<
boost::variant<
boost::shared_ptr<ToyModel>
>,
boost::variant<
boost::shared_ptr<BlueToy>,
boost::shared_ptr<RedToy>,
boost::shared_ptr<GreenToy>
>
> toyPicker;
如何使用 mpl 列表,以便为用户提供以下更简单的定义,然后在我的类实现中将其转换为上面的示例格式?
ToyPicker<
boost::mpl::list<
ToyModel
>,
boost::mpl::list<
BlueToy,
RedToy,
GreenToy
>
> toyPicker;
最佳答案
使用boost::mpl::transform与 boost::make_variant_over 结合使用诀窍是:
#include <boost/mpl/list.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/variant/variant.hpp>
template<class T>
struct add_shared_pointer
{
typedef boost::shared_ptr<T> type;
};
template<class Seq>
struct shared_ptr_variant
{
typedef typename boost::make_variant_over<
typename boost::mpl::transform<
Seq, add_shared_pointer<boost::mpl::_1>
>::type
>::type type;
};
关于c++ - 将 boost::mpl::list 应用于类型的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4476246/