'Append to existing tuple in c++
i am trying to make a thing to store types in list. The best thing is to use a tuple. then to get the type i use tuple_element_t. But the problem is when appending to the tuple so i can store more types. I found that you can append by tuple_cat by this is making a brand new tuple this is problem because i cannot assign it to the one in private section in class and cannot use it in functions inside class. Is there any way to do it?
#include <iostream>
#include <tuple>
using namespace std;
int main() {
auto main_tuple = make_tuple("Hello World");
auto appended_tuple = tuple_cat(main_tuple,make_tuple(1));
main_tuple = appended_tuple; //How to do this?
return 0;
}
Solution 1:[1]
At the point where main_tuple
is defined its underlying type is std::tuple<const char*>
.
The resulting type of appended_tuple
in the next line is std::tuple<const char*, int>
.
Since these two types don't match you can't assign them to each other.
As mentioned in the comments you may want to go for a container of 'wrappers' around your types instead -
most prominently std::any
or std::variant
.
Since you were asking about std::tuple
I assume you don't have to perform type-erasure (this is what std::any
does), so a possible solution could be the usage of a container like std::vector
with std::variant
:
#include <string>
#include <variant>
#include <vector>
int main()
{
using MyVariant = std::variant<int, std::string>;
using MyVector = std::vector<MyVariant>;
auto main_vector = MyVector{std::string("Hello World")};
auto appended_tuple = main_vector;
appended_tuple.push_back(456);
return 0;
}
In order now to check for the variant's inner type you can go for functions like get_if
, holds_alternative
, index
... - or write your own visitor that can be applied via std::visit
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Phlar |