Reputation: 496
I am trying to write a function like this
template<
bool b, RT = std::conditional_t<b,
std::tuple<int, int, int, int>,
std::tuple<int, int, int, int, double, double, double, double>
>
RT function()
{
int i1, i2, i3, i4;
if constexpr(b)
{
double i5, i6, i7, i8;
return { i1, i2, i3, i4, i5, i6, i7, i8 };
}
else
{
return { i1, i2, i3, i4 };
}
}
Is there a way to create a templated typedef for the tuple so that I can simplify the above function
template<typename T, int N>
using tuple_t = std::tuple<T, T, ... N1 times>
template<typename T1, int N1, typename T2, int N2>
using tuple_t = std::tuple<T1, T1, ... N1 times, T2, T2, ... N2 times>
Upvotes: 1
Views: 231
Reputation: 66230
Is too late to play?
To respond to your generic question
Is there a way to create a templated typedef for the tuple so that I can simplify the above function
template<typename T, int N> using tuple_t = std::tuple<T, T, ... N1 times> template<typename T1, int N1, typename T2, int N2> using tuple_t = std::tuple<T1, T1, ... N1 times, T2, T2, ... N2 times>
I propose the following, full and compilable, C++14 example
#include <tuple>
#include <utility>
template <typename T, std::size_t>
using get_type = T;
template <typename T, std::size_t ... Is>
constexpr std::tuple<get_type<T, Is>...>
get_tuple_t (std::index_sequence<Is...>);
template <typename T, std::size_t N>
using tuple_t_1 = decltype(get_tuple_t<T>(std::make_index_sequence<N>{}));
template <typename T1, std::size_t N1, typename T2, std::size_t N2>
using tuple_t_2 = decltype(std::tuple_cat(
std::declval<tuple_t_1<T1, N1>>(),
std::declval<tuple_t_1<T2, N2>>()));
int main ()
{
using t1a = tuple_t_1<int, 4u>;
using t1b = std::tuple<int, int, int, int>;
using t2a = tuple_t_2<int, 4u, double, 4u>;
using t2b = std::tuple<int, int, int, int, double, double, double, double>;
static_assert( std::is_same<t1a, t1b>::value, "!" );
static_assert( std::is_same<t2a, t2b>::value, "!" );
}
Upvotes: 1
Reputation: 9855
You can use return type deduction and replace the aggregate initialization with a call to make_tuple
:
template<bool b>
auto function()
{
int i1, i2, i3, i4;
if constexpr(b)
{
double i5, i6, i7, i8;
return std::make_tuple(i1, i2, i3, i4, i5, i6, i7, i8);
}
else
{
return std::make_tuple(i1, i2, i3, i4);
}
}
If you still need the return type you can simply make a trait:
template <bool b>
using return_t = decltype(function<b>());
Upvotes: 6