我已声明 aboost::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更高的优先级?