std::get using enum class as template argument

后端 未结 6 1608
孤街浪徒
孤街浪徒 2021-01-04 07:40

I\'m using a std::tuple and defined a class enum to somehow \"naming\" each of the tuple\'s fields, forgetting about their actual indexes.

So instead o

6条回答
  •  借酒劲吻你
    2021-01-04 08:13

    I'd like to add another answer because the original poster asked for a way to have a named access to elements of std::tuple through a class enum.

    It is possible to have a template argument of the type of a class enum (at least in GCC). This makes it possible to define your own get retrieving the element of a tuple given a class enum value. Below is an implementation casting this value to int, but you could also do something more fancy:

    #include 
    
    enum class names { A = 0, B, C };
    
    template< names n, class... Types >
    typename std::tuple_element( n ), std::tuple >::type&
        get( std::tuple& t )
    {
        return std::get< static_cast< std::size_t >( n ), Types... >( t );
    }
    
    int main( int, char** )
    {
        std::tuple< char, char, char > t( 'a', 'b', 'c' );
        char c = get( t );
    }
    

    Note that std::get has two more variants (one for const tuple&, one for tuple&&), which can be implemented exactly the same way.

提交回复
热议问题