我有一个容器变体如下:
typedef boost::variant<std::vector<int>, std::vector<std::string> > Container;
我从一个 ValueContainer 对象(一个 C 结构)填充一个 Container 对象,如下所示:
class ContainerAppender: public boost::static_visitor<>
{
public:
    void setValueToAppend(const Value* value){
        _value = value;
    }
    void operator()(std::vector<int>& container) const {
        container.push_back(_value->value.i);
    }
    void operator()(std::vector<std::string>& container) const {
        container.push_back(_value->value.s);
    }
    ...
private:
    const Value* _value;
};
void fillContainer(Container& container, ValueContainer* cContainer) {
    if(cContainer) {
        ContainerAppender append;
        for(int i = 0; i < cContainer->nunberOfValues; i++) {
            append.setValueToAppend(&cContainer->values[i]);
            boost::apply_visitor(append, container);
        }
    }
}
我不能随意更改 C 结构。
尽管容器类型永远不会改变,但我不喜欢填充容器的解决方案,因为我正在访问每个循环。感觉有更好的做法。你能帮我吗?
这是C联合:
typedef struct Value {
    union {
        int   i;
        const char* s;
    } value;
} Value_T;
typedef struct ValueContainer {
    Type type;
    unsigned int numberOfValues;
    Value *values;
} ValueContainer_T;