【发布时间】:2012-11-07 11:15:37
【问题描述】:
我声明了一个boost::variant,它接受三种类型:string、bool 和int。以下代码显示我的变体接受const char* 并将其转换为bool。 boost::variant 接受和转换不在其列表中的类型是正常行为吗?
#include <iostream>
#include "boost/variant/variant.hpp"
#include "boost/variant/apply_visitor.hpp"
using namespace std;
using namespace boost;
typedef variant<string, bool, int> MyVariant;
class TestVariant
: public boost::static_visitor<>
{
public:
void operator()(string &v) const
{
cout << "type: string -> " << v << endl;
}
template<typename U>
void operator()(U &v)const
{
cout << "type: other -> " << v << endl;
}
};
int main(int argc, char **argv)
{
MyVariant s1 = "some string";
apply_visitor(TestVariant(), s1);
MyVariant s2 = string("some string");
apply_visitor(TestVariant(), s2);
return 0;
}
输出:
类型:其他 -> 1
类型:字符串 -> 一些字符串
如果我从 MyVariant 中删除 bool 类型并将其更改为:
typedef variant<string, int> MyVariant;
const char* 不再转换为 bool。这次它被转换为string,这是新的输出:
类型:字符串 -> 一些字符串
类型:字符串 -> 一些字符串
这表示variant 尝试先将其他类型转换为bool,然后再转换为string。如果类型转换是不可避免的并且应该总是发生,有没有办法给string的转换提供更高的优先级?
【问题讨论】:
标签: c++ boost boost-variant