我有一个不同类型的 std::variant
,包括 int32_t
、int64_t
、float
、double
、std::string
和 bool
。
当我分配一个字符串文字(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/