【发布时间】:2022-11-10 17:18:04
【问题描述】:
在 MSVC 2022 和 C++17 下测试。应该在 gcc 和 clang 上工作,但未经测试。
#include <string>
#include <variant>
#include <type_traits>
/**
* rief Variant type to string.
* param T Variant type.
* param v Variant.
*
eturn Variant type as a string.
*/
template<typename T>
std::string variant_type_string(T v)
{
std::string result;
if constexpr(std::is_constructible_v<T, int>) { // Avoids compile error if variant does not contain this type.
if (std::holds_alternative<int>(v)) { // Runtime check of type that variant holds.
result = "int";
}
}
else if constexpr(std::is_constructible_v<T, std::string>) {
if (std::holds_alternative<std::string>(v)) {
result = "string";
}
}
else if constexpr(std::is_constructible_v<T, bool>) {
if (std::holds_alternative<bool>(v)) {
result = "bool";
}
}
else {
result = "?";
}
return result;
}
要使用:
std::variant<int, std::string> v { 42 };
std::cout << variant_type_string(v);
// Prints: int
【讨论】:
-
不是最好的解决方案。您应该
std::visit带有模板 lambda 的变体,并在其中打印类型,这将使其更通用。