c++ - 为什么 std::variant 在 GCC 8.5 和 GCC 12.1 上对于 `const char *` 文字的行为不同?

标签 c++ gcc c++17 std-variant

<分区>

#include <iostream>
#include <string>
#include <variant>

int main()
{
    std::variant<std::string, bool> v{ "hasta la vista" };
    std::cout << std::boolalpha << std::holds_alternative<std::string>(v) << ' ' << std::holds_alternative<bool>(v) << std::endl;
}

海湾合作委员会 12.1.1

$ g++ std_alternative.cpp 
$ ./a.out 
true false

海湾合作委员会 8.5.0

$ g++ -std=c++17 std_alternative.cpp 
$ ./a.out 
false true

为什么输出不同?根据 c++17,哪个是正确的?我应该怎么做才能使我的代码以相同的方式在两个版本的 GCC 上运行?

最佳答案

struct explicit_bool {
  bool b = false;
  template<class T,
   std::enable_if_t<std::is_same_v<T, bool>, bool> = true
  >
  explicit_bool( T v ):b(v){}
  explicit_bool(explicit_bool const&) noexcept=default;
  explicit_bool& operator=(explicit_bool const&)& noexcept=default;
  explicit_bool()noexcept=default;
  ~explicit_bool()noexcept=default;
  bool operator!() const { return !b; }
  explicit operator bool() const { return b; }
};

存储其中一个(而不是 bool )。

它只接受实际的 bool s等explicit_bool s 作为参数。

您可能必须添加一些显式转换到-从 bool执行此操作后在您的代码中。您可能会对 (bool) 感兴趣因为 Actor 总是做与 static_cast<bool> 完全相同的事情与 C++ 风格的转换相比,与许多其他 C 风格的转换不同;这可以减轻痛苦。另一个选择是 !! , 它将大多数类型转换为 bool含蓄地。

关于c++ - 为什么 std::variant 在 GCC 8.5 和 GCC 12.1 上对于 `const char *` 文字的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73294887/

相关文章:

C++ 编译时子串

c++ - 如何通过通用引用或 std::forward 将这三个 C++ 模板函数合并为一个?

c++ - 如何使用glsl改变顶点位置

c++ - 迭代 vector 以更新 word_counter

c++ - Delphi/C++ Builder - 在 TDBGrid 中设置事件/选定行颜色

linux - 如何避免二进制文件中的 STT_GNU_IFUNC 符号?

c++ - live555 onDemandServer 流式传输多播

c - 为什么 sscanf 不填充变量?

c++ - 为什么 GCC -O3 在 std::deque 上使用过滤器迭代器导致无限的 std::distance?

c++ - 如何检查名称是 C++17 中的别名还是引用?