boost::variant 类型转换
我有来自 boost 库的以下变体:
typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> variant;
现在我想从 struct 节点
中声明为 'value
' 的变量获取值,所以我认为我可以工作通用并按如下方式调用函数:find_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;
}
}
}
}
I have the following variant from the boost lib:
typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> variant;
Now I want to get a value from a variable declared as 'value
' in a struct node
, so I thought I could work generic and call the function as such: find_attribute<long>(attribute);
, however the compiler says it cannot cast from variant to long or any other type I give it. What am I doing wrong?
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;
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须使用
boost::get(variant)
从变量中获取值。You have to use
boost::get<type>(variant)
to get the value from a variant.也许对您来说更好的方法是使用访问者 - 所以你只需编写一次 find_attribute :
Maybe a better way for you is to use visitors - so you will have to write find_attribute only once: