Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gaining access to the tuple by string template param

A standard tuple in C++ 11 allows access by the integer template param like this:

tuple<int, double> test;
test.get<1>();

but if I want get access by the string template param:

test.get<"first">()

how can I implement it?

like image 623
COUNTERKILL Avatar asked Dec 13 '25 00:12

COUNTERKILL


1 Answers

You can create custom constexpr cast function. I just wanted to show that what the OP wants is (almost) possible.

#include <tuple>
#include <cstring>

constexpr size_t my_cast(const char * text)
{
    return !std::strcmp(text, "first") ? 1 :
           !std::strcmp(text, "second") ? 2 :
           !std::strcmp(text, "third") ? 3 :
           !std::strcmp(text, "fourth") ? 4 :
           5;
}

int main()
{
    std::tuple<int, double> test;
    std::get<my_cast("first")>(test);
    return 0;
}

This can be compiled with C++11 (C++14) in GCC 4.9.2. Doesn't compile in Visual Studio 2015.

like image 159
Lukáš Bednařík Avatar answered Dec 15 '25 12:12

Lukáš Bednařík



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!