是否可以将变体的索引作为 constexpr 变量获取?
Is it possible to get the index of a variant as a constexpr variable?
我有以下代码 (play with example). It checks what the underlying value of a variant is and receives this underlying value using get。如您所见,代码变得非常重复。
#include <variant>
#include <string>
#include <iostream>
#include <vector>
int main()
{
std::variant<int, double, std::string> v;
// v holds a string
v = "hi there!";
switch(v.index()) {
case 0:
{ // brackets to avoid cross initialization
int i = std::get<int>(v);
// handle int
}
break;
case 1:
{
double d = std::get<double>(v);
// handle double
}
break;
case 2:
{
std::string s = std::get<std::string>(v);
// handle string
}
break;
}
}
问题: 有什么方法可以将变体的索引作为 constexpr
变量吗?我想做这样的事情:
// what I would like to do
// auto val_of_v = std::get<v.index()>(v);
// Error: template argument deduction/substitution failed
// in 'constexpr' expansion of v<...>::index()
相关 Post: .
仅当变体是 constexpr 本身时:
constexpr std::variant<int, double> v{24};
auto a = std::get<v.index()>(v);
否则信息只能在运行时才知道
您正在寻找的是 std::visit
,它是为您实现该转换的图书馆设施:
std::variant<int, double, std::string> v;
// v holds a string
v = "hi there!";
std::visit([](auto&& x){
// x is whatever the variant was holding (could be int, double, or string)
}, v);
我有以下代码 (play with example). It checks what the underlying value of a variant is and receives this underlying value using get。如您所见,代码变得非常重复。
#include <variant>
#include <string>
#include <iostream>
#include <vector>
int main()
{
std::variant<int, double, std::string> v;
// v holds a string
v = "hi there!";
switch(v.index()) {
case 0:
{ // brackets to avoid cross initialization
int i = std::get<int>(v);
// handle int
}
break;
case 1:
{
double d = std::get<double>(v);
// handle double
}
break;
case 2:
{
std::string s = std::get<std::string>(v);
// handle string
}
break;
}
}
问题: 有什么方法可以将变体的索引作为 constexpr
变量吗?我想做这样的事情:
// what I would like to do
// auto val_of_v = std::get<v.index()>(v);
// Error: template argument deduction/substitution failed
// in 'constexpr' expansion of v<...>::index()
相关 Post:
仅当变体是 constexpr 本身时:
constexpr std::variant<int, double> v{24};
auto a = std::get<v.index()>(v);
否则信息只能在运行时才知道
您正在寻找的是 std::visit
,它是为您实现该转换的图书馆设施:
std::variant<int, double, std::string> v;
// v holds a string
v = "hi there!";
std::visit([](auto&& x){
// x is whatever the variant was holding (could be int, double, or string)
}, v);