使用std :: get <index>访问std :: variant

时间:2018-08-01 01:15:08

标签: c++ std c++17 variant

如何使用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' 

Wandbox

已更新以询问如何解决,而不是错误消息是什么意思。

2 个答案:

答案 0 :(得分:6)

std::get<>适用于请求在编译时已知的索引。

如果您需要在运行时对变量值进行操作,惯用的方法是将访问者与std::visit一起使用。

#include <iostream>
#include <variant>
#include <string>

struct output_visitor
{
    template< typename T >
    void operator() ( const T& value ) const
    {
        std::cout << value;
    }   
};

int main()
{
    std::variant<int, std::string> f( 0 );

    std::visit( output_visitor{}, f );
}

答案 1 :(得分:3)

gcc 8.1's error output还包括以下说明:

<source>:10:29: error: the value of 'fi' is not usable in a constant expression
    auto ff = std::get<fi>(f);
                        ^
<source>:9:23: note: 'fi' was not initialized with a constant expression
   const std::size_t fi = f.index();

整数模板参数必须是常量表达式。 f不是常量表达式,因此对其非静态成员函数的调用不是常量表达式,因此fi不是常量表达式。

您可以通过以下方式获得更好的错误消息:

constexpr std::size_t fi = f.index();

仅当get<fi>(f)也被声明为f时,代码constexpr才有效;但这只有在变体中的所有类型都具有琐碎的析构函数的情况下才有可能,而std::string没有。