boost::variant 当 bool 显示为可能的类型时,会给出错误的结果
boost::variant gives wrong result when bool appears as possible type
工作的代码如下:
#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 语句不成功。问题出在哪里?
在代码中,当std::string
和bool
都位于变体类型中时,values["b"] = "bstring";
会创建一个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)
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 分段错误当我试图运行程序时出错
- 执行set_difference时出错:变量结果不是结构