是否可以将变体的索引作为 constexpr 变量获取?

Is it possible to get the index of a variant as a constexpr variable?

本文关键字:constexpr 变量 获取 索引 是否      更新时间:2023-10-16

我有以下代码(使用示例(。它检查变体的基础值是什么,并使用 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()

延伸阅读》在 std::variant 中按类型获取索引。

仅当变体是 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);