在while循环中连接值出错了

时间:2010-12-15 09:47:54

标签: c++ string-concatenation boost-bind

我有boost::variant,其中包含各种类型,我有一个字符串需要如下所示: type = D,S 。变体中的值分别为D和S,键为'type'。它是map<std::string, std::vector<variant> >,我现在正在迭代vector<variant>部分

现在我首先将static_visitor应用于我的变体以进行适当的转换,在这种情况下可能不需要,但对于其他类型,它需要转换为字符串。

然后我调用这个名为ConcatValues的函数,它是辅助类的一部分。这个类定义了vector<string> v_accumulator来保存临时结果,因为这个函数可能在while循环中被多次调用,我想以逗号分隔值列表结束。

然而问题是我的向量v_accumulator在每次函数调用时总是为空?这有什么意义,因为它是一个类变量。

while(variant_values_iterator != values.end())
{
          variant var = *variant_values_iterator;
        boost::apply_visitor( add_node_value_visitor( boost::bind(&SerializerHelper::ConcatValues, helper, _1, _2), key, result), var);
        variant_values_iterator++;
}



std::string SerializerHelper::ConcatValues(std::string str, std::string key)
{
    v_accumulator.push_back(str); //the previous value is not in this vector???
    std::stringstream ss;
    std::vector<std::string>::iterator it = v_accumulator.begin();

    ss << key;
    ss << "=";

    for(;it != v_accumulator.end(); it++)
    {
        ss << *it;
        if (*it == v_accumulator.back())
            break;
        ss << ",";
    }

    return ss.str();

}


class SerializerHelper
{
public:
    std::string ConcatValues(std::string str, std::string key);

private:
    std::vector<std::string> v_accumulator;
};

也许有一种更简单的方法可以在原始键/值对的值部分中连接D,S的值?

1 个答案:

答案 0 :(得分:4)

问题可能是,虽然v_accumulator是类成员,但boost::bind默认复制其参数。这意味着ConcatValues会在helper副本上调用,v_accumulator具有自己的boost::ref向量。

如果您想要参考,则必须使用boost::apply_visitor(add_node_value_visitor( boost::bind(&SerializerHelper::ConcatValues, boost::ref(helper), _1, _2), key, result), var);

{{1}}
相关问题