vendredi 1 juillet 2016

Can I rely on empty parameter packs to be expanded properly?

The following code defines function subst_first, which substitutes the first elements of an array of ints by the contents of another array. It works under gcc and clang (live demo). For cases //1, //2 and //3 one of the generated index_sequence's is empty. Consequently one of the parameter packs at //4 has zero elements. This makes me feel uneasy. Can I rely on this behavior to be standard conforming?

template<size_t n, size_t ... S1, size_t ... S2>
constexpr
std::array<int,3>
subst_first_impl( std::array<int,n> const &v1,
                  std::array<int,3> const &v2,
                  size_t min_n,
                  std::index_sequence<S1...>,
                  std::index_sequence<S2...> )
{    return std::array<int,3>; } // 4

template<size_t n>
constexpr
std::array<int,3>
subst_first( std::array<int,n> const &v1,
             std::array<int,3> const &v2 )
{   auto const min_n= std::min( size_t(3), n );
    return subst_first_impl( v1, v2, min_n,
                             std::make_index_sequence< min_n >(),
                             std::make_index_sequence< size_t(3) - min_n >() );
}

int main(){
    constexpr std::array<int,3>  a11;

    constexpr std::array<int,2>  b14;
    constexpr std::array<int,3>  b26;
    constexpr std::array<int,4>  b39;
    constexpr std::array<int,0>  b4{};

    constexpr auto b1a1= subst_first( b1, a1 );
    // ==> 4, 5, 3

    constexpr auto b2a1= subst_first( b2, a1 ); // 1
    // ==> 6, 7, 8

    constexpr auto b3a1= subst_first( b3, a1 ); // 2
    // ==> 9, 10, 11

    constexpr auto b4a1= subst_first( b4, a1 ); // 3
    // ==> 1, 2, 3
}

Note: I am not looking for a solution for substituting elements of arrays. I am interested in the behavior of index_sequence's and parameter packs.

Aucun commentaire:

Enregistrer un commentaire