构造模板化的元组类型

Bil*_*tor 1 c++ templates tuples template-meta-programming variadic-templates

我正在尝试编写这样的函数

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 };
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以为元组创建模板化的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>
Run Code Online (Sandbox Code Playgroud)

Tim*_*imo 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果仍然需要返回类型,则可以简单地做一个特征:

template <bool b>
using return_t = decltype(function<b>());
Run Code Online (Sandbox Code Playgroud)