首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >利用boost-variant通过boost::mpl::for_each创建泛型工厂方法

利用boost-variant通过boost::mpl::for_each创建泛型工厂方法
EN

Stack Overflow用户
提问于 2016-09-08 14:33:37
回答 1查看 223关注 0票数 0

在我的一个项目中,我需要将boost::variant which()-Function的int映射到boost::variant的类型。

由于某些原因,地图不包含正确的TVar类型?为什么会这样呢?

代码语言:javascript
复制
#include <boost/mpl/for_each.hpp>
#include <boost/variant.hpp>
#include <string>
#include <map>
#include <iostream>

using TVar = boost::variant<std::string, int, double>;

namespace Helper {
    struct createMap {
        std::map<int, TVar> map;
        template<typename T>
        void operator()(const T& t) {
            auto x = TVar(t);
            map[x.which()] = x;
        }
    };
}


bool createObject(int which, TVar& var) {
    Helper::createMap c;
    boost::mpl::for_each<TVar::types>(boost::ref(c));
    if (c.map.find(which) != c.map.end()) {
        var = c.map[which];
        return true;
    }
    else {
        return false;
    }
}

int main() {
    TVar var;
    bool ok=createObject(0, var);
    return 0;
}
EN

回答 1

Stack Overflow用户

发布于 2018-09-19 02:18:21

如果我理解正确的话,您希望为变量分配一个默认构造的值,该值将在运行时通过索引变量的可能类型来确定,那么您将查找以下内容:

代码语言:javascript
复制
#include <boost/mpl/at.hpp>
#include <boost/mpl/size.hpp>

#include <boost/variant.hpp>
#include <string>


template <typename VariantT, int L, int R>
struct assign_default_constructed
{
    static bool call(int which, VariantT& var)
    {
        static int const M = L + (R - L + 1) / 2;
        if (which < M) {
            return assign_default_constructed<VariantT, L, M - 1>::call(which, var);
        }
        else {
            return assign_default_constructed<VariantT, M, R>::call(which, var);
        }
    }
};

template <typename VariantT, int I>
struct assign_default_constructed<VariantT, I, I>
{
    static bool call(int /*which*/, VariantT& var)
    {
        //assert(which == I);
        var = typename boost::mpl::at_c<typename VariantT::types, I>::type();
        return true;
    }
};

template <typename VariantT>
bool createObject(int which, VariantT& var)
{
    static int const N = boost::mpl::size<typename VariantT::types>::value;
    if (which < 0 || which >= N) return false;
    return assign_default_constructed<VariantT, 0, N - 1>::call(which, var);
}

int main() {
    boost::variant<std::string, int, double> var;
    bool ok = createObject(1, var);
    return ok ? var.which() : -1;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39384027

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档