c++ - mingw 与 msvc 关于字符串文字的隐式转换

标签 c++ c++17 string-literals

我有一个不同类型的 std::variant ,包括 int32_tint64_tfloatdoublestd::stringbool。 当我分配一个字符串文字(const char*,此变体中不存在)时,我假设它将隐式转换为 std::string 并且它的工作方式如下我期望使用 MinGW(9.0.0 64 位)。但使用 MSVC(2019 64 位) 时,它会隐式转换为 bool。 如果我显式地将其转换为 std::string ,然后将其分配给变体,则它在两个编译器中都可以正常工作。

这是代码

#include <iostream>
#include <variant>

#if defined(__MINGW64__) || defined(__MINGW32__)
#define CMP_NAME "[ MinGW ]"
#elif defined(_MSC_VER)
#define CMP_NAME "[ MSVC ]"
#else
#define CMP_NAME "[ Others ]"
#endif

using KInt32 = int32_t;
using KInt64 = int64_t;
using KFloat = float;
using KDouble = double;
using KString = std::string;
using KBoolean = bool;

using Variant = std::variant<
    KInt32      /*0*/,
    KInt64      /*1*/,
    KFloat      /*2*/,
    KDouble     /*3*/,
    KString     /*4*/,
    KBoolean    /*5*/
>;

int main()
{
    //passing a const char* to Variant [target is to initialize as KString]
    Variant var = "ABCDE";
    std::cout << "Build With Compiler Set " CMP_NAME << std::endl;
    std::cout << "index = " << var.index() << std::endl;
    try{
        KString &str = std::get<KString>(var);
        std::cout << "\t[string = " << str << "]" << std::endl;
    }
    catch(const std::exception &e){
        std::cout << "\t[exception = " << e.what() << "]" << std::endl;
    }
    return 0;
}

这是输出
使用 MinGW 9.0.0

     Build With Compiler Set [ MSVC ]
     index = 5
          [exception = bad variant access]

与 MSVC 2019 一起

Build With Compiler Set [ MinGW ]
index = 4
    [string = ABCDE]

索引 4 表示 KString (又名 std::string),索引 5 表示 KBoolean (又名 bool) >).
所以我的问题是为什么两个编译器给出不同的结果?

最佳答案

在 C++20 中,变体的行为针对这种具体情况发生了变化。 请参阅What is the best way to disable implicit conversion from pointer types to bool when constructing an std::variant?进行更长时间的讨论。

关于c++ - mingw 与 msvc 关于字符串文字的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70593988/

相关文章:

c++ - 用于检查枚举类是否可用的简单宏

c++ - 如何让一个变量依赖于一个类中的其他变量?

C++17 文件系统调用产生段错误

string - Rust 中的 r #""# 运算符是什么?

c++ - boost_asio_handler_invoke_helpers::invoke 是否仍然是在 boost asio 1.70 中调用完成处理程序的受支持方式?

c++ - 如何从 vector <char>中提取不同数据类型的子 vector ?

c++ - 问候,我的代码中有语法问题。你能帮助我吗?

c# - 如何分隔字符串中的段落?

c++ - 编码接受来自未指定来源的随机位的密码算法

c++ - C++ 14和c++ 17中相同代码的不同输出