boost::variant<int,std::string,bool>
当我遇到意外行为时,我正在与它的访问者一起工作:字符串和布尔值是可比较的。我不知道,为什么它会这样工作,但我发现它很有趣。我唯一的想法是带有布尔值的变体被解释为字符?有人可以给我解释一下吗?比较访客:
#include <iostream>
#include <algorithm>
#include <vector>
#include <boost/variant.hpp>
#include <boost/function.hpp>
struct my_less : boost::static_visitor<bool*>
{
template<typename T>
bool* operator()(T a, T b) const
{
return a<b ? new bool(true) : new bool(false);
}
template<typename T, typename U>
bool* operator()(T a, U b) const
{
return NULL;
}
};
int main()
{
typedef boost::variant<int,bool,std::string> datatype;
datatype *a = new datatype(false);
datatype *b = new datatype("abc");
my_less cmp;
bool* val = boost::apply_visitor(cmp,*a,*b);
if(val)
{
std::cout << *val;
}
else
{
std::cout << "NULL";
}
}
编辑这是带有一些测试用例的扩展主要功能:
void show_result(bool* val)
{
if(val)
{
std::cout << *val << std::endl;
}
else
{
std::cout << "NULL" << std::endl;
}
}
int main()
{
//std::string a = "bbb";
//bool b = true;
//std::cout << b<a; //compilation error
typedef boost::variant<int,bool,std::string> datatype;
datatype int_value_1(4);
datatype int_value_2(3);
datatype string_value("abc");
datatype bool_value(true);
my_less cmp;
std::cout<<"First result, compare ints 4 and 3:"<<std::endl;
bool* val = boost::apply_visitor(cmp,int_value_1,int_value_2);
show_result(val);
std::cout<<"Second result, compare int to string 4 to abc " << std::endl;
val = boost::apply_visitor(cmp,int_value_1,string_value);
show_result(val);
std::cout <<"Third result, int 4 to bool true:" << std::endl;
val = boost::apply_visitor(cmp,int_value_1,bool_value);
show_result(val);
std::cout<<"Fourth result, string abc to bool true" << std::endl;
val = boost::apply_visitor(cmp,string_value,bool_value);
show_result(val);
}
输出:
First result, compare ints 4 and 3:
0
Second result, compare int to string 4 to abc
NULL
Third result, int 4 to bool true:
NULL
Fourth result, string abc to bool true
0