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?
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?
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.
First of all, std::tuple::get
is not a member function. There is a non-member function std::get
.
Given,
std::tuple<int, double> test;
You cannot get the first element by using:
std::get<"first">(test);
You can use other mnemonics:
const int First = 0;
const int Second = 1;
std::get<First>(test);
std::get<Second>(test);
if that makes the code more readable for you.
R Sahu gives a couple of good mnemonics, I wanted to add another though. You can use a C style enum (i.e. non-class enum):
enum TupleColumns { FIRST, SECOND };
std::get<FIRST>(test);
If you combine enums with a smart enum reflection library like so: https://github.com/krabicezpapundeklu/smart_enum, then you can create a set of enums that have automatic conversions to and from string. So you could automatically convert column names into enums and access your tuple that way.
All this requires you to commit to your column names and orders at compile time. In addition, you'll always need to use string literals or constexpr functions, so that you can get the enum value as constexpr to use it this way.
constexpr TupleColumns f(const char *);
constexpr auto e = f("first");
std::get<e>(test);
I should probably add a warning at this point: this is all a fairly deep rabbit hole, fairly strong C++ is required. I probably would look for a different solution in the bigger picture, but I don't know your bigger picture well enough, nor do I know the level of your C++ nor your colleagues (assuming you have them).