有效的代码如下:
#include <boost/variant.hpp>
#include <string>
#include <map>
#include <iostream>
int main(int argc, char** argv) {
std::map<std::string, boost::variant<int, std::string> > values;
values["a"] = 10;
values["b"] = "bstring";
values["c"] = "cstring";
for (const auto &p : values) {
std::cout << p.first << " = ";
if (p.second.type() == typeid(std::string)) {
std::cout << boost::get<std::string>( p.second ) << " (found string)" << std::endl;
} else if ( p.second.type() == typeid(int)) {
std::cout << boost::get<int>( p.second ) << " (found int)" << std::endl;
} else if ( p.second.type() == typeid(bool)) {
std::cout << boost::get<bool>( p.second ) << " (found bool)" << std::endl;
} else {
std::cout << " not supported type " << std::endl;
}
}
}
输出(g ++ test.cpp -std = c ++ 11):
a = 10
b = bstring
c = cstring
除了定义std :: map
的行之外,不起作用的代码完全相同将地图定义的行修改为:
std::map<std::string, boost::variant<int, std::string, bool> > values;
输出不同:
a = 10
b = c =
引用std :: string比较的if语句不成功。有什么问题?
答案 0 :(得分:2)
在代码中,当values["b"] = "bstring";
和bool
都属于变体类型时,std::string
会创建bool
值。
修正为values["b"] = std::string("bstring");
。
或者,在C++14中:
using namespace std::string_literals;
values["b"] = "bstring"s;
众所周知,字符串文字更好地转换为bool
而不是std::string
:
#include <iostream>
#include <string>
void f(std::string) { std::cout << __PRETTY_FUNCTION__ << '\n'; }
void f(std::string const&) { std::cout << __PRETTY_FUNCTION__ << '\n'; }
void f(bool) { std::cout << __PRETTY_FUNCTION__ << '\n'; }
int main() {
f("hello");
}
输出:
void f(bool)