我正在尝试编写这样的函数
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 };
}
}
是否可以为元组创建模板化的typedef,以便简化上述功能
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>
答案 0 :(得分:6)
您可以使用返回类型推导,并用对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);
}
}
如果您仍然需要返回类型,则只需做一个特征:
template <bool b>
using return_t = decltype(function<b>());
答案 1 :(得分:1)
玩太晚了吗?
回答您的一般性问题
是否可以为元组创建模板化的typedef,以便简化上述功能
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>
我提出了以下完整且可编译的C ++ 14示例
#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, "!" );
}