如何使用v.index()
和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'
更新为询问如何解决问题而非错误信息的含义。
涉及IT技术相关内容,建议您提供更具体的翻译需求以便我更好地进行翻译。
0
是 variant 的有效索引;第1点(这个情况)并没有说明索引参数的类型。你可以使用0
、0L
、(size_t)0
等等。第2点讨论了get<long>(f)
,这将是不合法的。 - M.M