2

我有一个需要 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;
4

2 回答 2

5

boost::mpl::transformboost::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;
};
于 2010-12-18T09:40:35.220 回答
0

查看boost::make_variant_over它可以满足您的需要。

于 2010-12-18T03:15:35.067 回答