c++ - 将 boost::mpl::list 应用于类型的模板参数

标签 c++ boost boost-mpl boost-variant

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

关于c++ - 将 boost::mpl::list 应用于类型的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4476246/

相关文章:

c++ - 即使使用 FILE_FLAG_OVERLAPPED,Windows WriteFile 也会阻塞

c++ - 从 const 引用初始化非常量对象时防止复制

c++ - 获取 Boost Proto 子表达式的标签类型

c++ - 有没有办法恢复嵌入在 boost mpl 引用中的原始模板模板类?

c++ - 将一个 mpl 序列序列转换成一个 trie

c++ - visual studio 在运行之前不构建应用程序

c++ - GSL 中是否有 `numpy.minimum` 等价物?

c++ - 您最喜欢/推荐的使用 Boost 进行单元测试的项目结构和文件结构是什么?

c++ - UDP Boost ASIO 异步客户端挂起

c++ - mpl::transform on boost::fusion::tuple