boost :: variant成员另一个boost :: variant的子集

时间:2013-03-11 09:41:58

标签: c++ boost c++98

我正在使用一个相当笨拙的c接口来存储集合。类LowLevelStorer表示我为此接口编写的包装器。 Storer类是一个高级类,它关注Data。它会将数据缓存并捆绑成更复杂的数据类型,只有LowLevelStorer才知道。我的其余代码只能使用Data进行查询,并且不了解LowLevelData

在下面的示例代码中,我希望Data变体中的成员包含在LowLevelData变体中。有没有办法指明这个我是怎么做到的?

我真正不明白的是为什么下面的代码编译,实际上,为什么它实际上正常工作。也就是说,void operator()(const SimplePath&, const Data& data) const接受数据引用,但在调用void operator()(const LowLevelData& data) const时似乎正确地将其转换为LowLevelData对象。怎么会这样?

我的数据对象幕后是否有很多副本?

#include "boost/variant.hpp"
#include "boost/variant/apply_visitor.hpp"
#include <vector>

class Complex{};
typedef boost::variant< std::vector<Complex>, std::vector<int>, std::vector<std::string> > LowLevelData;

class LowLevelStorer
{
public:
    LowLevelStorer(): _storeVisitor(StoreVisitor()){}

    void operator()(const LowLevelData& data) const 
    {
        boost::apply_visitor(_storeVisitor, data);
    }

private:
    class StoreVisitor: public boost::static_visitor<>
    {
    public:
        void operator()(const std::vector<Complex>&) const {}

        void operator()(const std::vector<int>& i) const {}

        void operator()(const std::vector<std::string>&) const {}
    };

    StoreVisitor _storeVisitor;
};


struct SimplePath{};
struct BundlePath{};
typedef boost::variant< SimplePath, BundlePath > Path;

typedef boost::variant< std::vector<std::string>, std::vector<int> > Data;

class Storer
{
public:
    Storer(const LowLevelStorer& lowLevelStorer): _converter(Converter(lowLevelStorer)){}

    void operator()(const Path& path, const Data& data) const 
    {
        boost::apply_visitor(_converter, path, data);
    }

private:
    class Converter: public boost::static_visitor<>
    {
    public:
        Converter(const LowLevelStorer& lowLevelStorer): _lowLevelStorer(lowLevelStorer){}

        void operator()(const SimplePath&, const Data& data) const {
            _lowLevelStorer(data);
        }

        void operator()(const BundlePath&, const Data& data) const {
            _lowLevelStorer(std::vector<Complex>());
        }
    private:
        const LowLevelStorer _lowLevelStorer;
    };

    const Converter _converter;
};

int main()
{
    Storer storer((LowLevelStorer()));
    std::vector<int> v;
    v.push_back(13);
    storer(Path(SimplePath()),v);

    return 0;
}

1 个答案:

答案 0 :(得分:2)

当你提供参数作为我怀疑的另一个时,它需要一个变体的原因是因为你的两个变种都有共同的所有类型,这使你的变体可以相互转换。

我认为只使用一种变体与所有三种类型并完全跳过另一种变体完全没问题,看第二种只是第一种类型的子集。

相关问题