是否可以将变体的索引作为 constexpr 变量获取?
Is it possible to get the index of a variant as a constexpr variable?
我有以下代码(使用示例(。它检查变体的基础值是什么,并使用 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);
相关文章:
- vs 2015 constexpr变量不恒定,但与2019相比还好吗
- constexpr函数中的静态constexpr变量
- 有时可以在 constexpr 上下文中使用非 constexpr 变量?
- 错误:constexpr 变量'struct2Var'必须由常量表达式初始化
- 是否使用静态 constexpr 变量 odr?
- 是否可以将变体的索引作为 constexpr 变量获取?
- 非 constexpr 变量模板的开销是否为零?
- Constexpr变量不是编译时值
- 为什么非成员静态 constexpr 变量不是隐式内联的?
- 使用 constinit 变量初始化 constexpr 变量
- 这是通过初始化 constexpr 变量来标记编译错误的合理跳转
- "static initialization order fiasco"是 constexpr 变量的问题吗?
- lambda 表达式中引用捕获的 constexpr 变量和非显式捕获的 constexpr 变量之间的区别
- is_constant_evaluated() 应该产生 constexpr 变量吗?
- 是否都是隐式内联的 constexpr 变量
- 为全局constexpr变量生成唯一值
- 错误!Constexpr变量必须通过常数表达式constexpr初始化
- 为什么我不能使用 msvc 在模板类中声明静态 constexpr 变量?
- 如果Constexpr - clang vs.GCC,则非constexpr变量
- Clang 在编译时不会计算非 constexpr 变量的 constexpr 函数的值