Reputation: 1329
I want to have a method to build a tuple with variable number or entries based on how many entries an object has in a member variable container (e.g. vector).
This is what I've got as my best result. Not working, however. I'm obviously missing something in return value construction. Let's say m_values
is a container with values I want to put into a tuple and return.
template<typename... T>
std::tuple<T...> getValuesTuple()
{
if (m_values[0].isValid())
{
return buildReturnTuple(0);
}
return std::tuple<T...>();
}
template<typename... T>
std::tuple<T...> buildReturnTuple(size_t i)
{
if (i + 1 < MAX_VALUES && m_values[i + 1].isValid())
{
return std::tuple<T, T...>(m_values[i], buildReturnTuple(i + 1));
}
return std::tuple<T...>(m_values[i]...);
}
Thank you in advance!
Upvotes: 0
Views: 461
Reputation: 275976
The types of variables in C++ is a compile time property.
The type a function returns is a compile time property.
What you are asking to do cannot be done, because a 2 element tuple is a different type than a 3 element tuple.
There are related techniques based off std::variant
or even std::any
but they are unlikely to be what you want.
You need to step back and look at your motivating problem that made you want the data stored as a tuple here and find a different path.
Upvotes: 0
Reputation: 10315
If you know size of array at compile time, it can be done in way like this:
#include <array>
#include <tuple>
#include <utility>
struct MyType {};
constexpr auto my_type_to_any_other_type(const MyType&) {
// use if constexpr to return desired types
return 0;
}
template<std::size_t N, std::size_t... Idx>
constexpr auto array_to_tuple_helper(const std::array<MyType, N>& a, std::index_sequence<Idx...>) {
return std::make_tuple(my_type_to_any_other_type(a[Idx])...);
}
template<std::size_t N>
constexpr auto array_to_tuple(const std::array<MyType, N>& a) {
return array_to_tuple_helper(a, std::make_index_sequence<N>{});
}
int main () {
auto t = array_to_tuple(std::array<MyType, 1>{ MyType{} });
return 0;
}
Upvotes: 2