c++ - boost::variant 类型转换

标签 c++ variant

我有来自 boost 库的以下变体:

typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> variant;

现在我想从声明为“value”的变量中获取一个值' 在 struct node ,所以我想我可以工作通用并调用函数:find_attribute<long>(attribute); ,但是编译器说它不能从 variant 转换为 long 或我给它的任何其他类型。我做错了什么?

template <typename T>
T find_attribute(const std::string& attribute)
{

    std::vector<boost::shared_ptr<node> >::iterator nodes_iter = _request->begin();

    for (; nodes_iter != _request->end(); nodes_iter++)
    {
        std::vector<node::attrib>::iterator att_iter = (*nodes_iter)->attributes.begin();
        for (; att_iter != att_iter; (*nodes_iter)->attributes.end())
        {
            if (att_iter->key.compare(attribute) == 0)
            {
                return (T)att_iter->value; //even explicit cast doesn't wrok??
                //return temp;
            }

        }

    }
}

最佳答案

你必须使用 boost::get<type>(variant) 从变体中获取值。

关于c++ - boost::variant 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4539573/

相关文章:

c++ - 将输入值与 vector 中的值进行比较

c++ - 多版本资源

JavaScript 内存不足错误 : UDF thread memory limit exceeded-Snowflake

c++ - 有没有希望有效地调用 std::variant 上的公共(public)基类方法?

c++ - 关于如何在具有单个参数的变体构造中选择替代方案?

c++ - 从左到右的关联性是什么意思?

c++ - 在 C++ 中测量 CPU 时间

c++ - 字符串输入/输出

c++ - COM,包含 BSTR 的 VARIANT。谁分配?

c# - 将 VB6 变体分配给对象