如何使用v.index()then访问变体的成员std::get<index>(v)?
当变体具有多个相同类型的条目时很有用。
以下不起作用。此代码不能在 GCC 或 clang 上编译
#include <iostream>
#include <variant>
#include <string>
#include <sstream>
typedef std::variant<int, int, std::string> foo;
std::string bar(const foo f) {
const std::size_t fi = f.index();
auto ff = std::get<fi>(f);
std::ostringstream ss;
ss << "Index:" << fi << " Value: " << ff;
return ss.str();
}
int main()
{
foo f( 0 );
std::cout << bar(f);
}
std::get 当然有很多版本,所以错误信息很长。
gcc 抱怨(对于 get<> 的每个版本)
prog.cc:10:29: error: the value of 'fi' is not usable in a constant expression
auto ff = std::get<fi>(f);
^
prog.cc:9:23: note: 'fi' was not initialized with a constant expression
const std::size_t fi = f.index();
^~
prog.cc:10:29: note: in template argument for type 'long unsigned int'
auto ff = std::get<fi>(f);
Clang 抱怨(对于 get<> 的每个版本)(根据具体情况重新 _Tp 或 _Ip)
candidate template ignored: invalid explicitly-specified argument for template parameter '_Tp'
更新询问如何解决而不是错误消息是什么意思。