4

I have a function with two parameter packs where I can control what ends up in each one of them.

#include <iostream>
using namespace std;

template< typename... Args0, typename... Args1>
void func( Args0&&... args0, Args1&&... args1 ) {
    cout << "args0: ";
    (cout << ... << args0);
    cout << '\n';

    cout << "args1: ";
    (cout << ... << args1);
    cout << '\n';
}

int main() {
    func<int, int, int>( 1, 2, 3, 4, 5, 6 );
    cout << '\n';
    func<int, int>( 1, 2, 3, 4, 5, 6 );
}

//Output from both GCC and Visual Studio.
//  args0: 123
//  args1: 456
//
//  args0: 12
//  args1: 3456

Demo: https://godbolt.org/z/n6T3h9dr5

This works both in GCC and Visual Studio C++.

I would have thought this was not valid code. Is this "undefined behaviour", or can I safely start utilizing this?

Edit: Added example of usage

template<typename... Args>
ostream & operator<<( ostream & out, const tuple<Args...> & tup ) {
    auto func = [&]( const auto&... args_first, const auto&... arg_last ) {
        out << "{ ";
        ((out << args_first << " , "), ...);
        ((out << arg_last), ...);
        out << " }";
    };
    apply( func, take_firsts( tup ), take_last( tup ) );
    return out;
}

Demo: https://godbolt.org/z/8nK61aMn5

Generic Name
  • 1,083
  • 1
  • 12
  • 19
  • 3
    If you have some spare time, consider watching this talk by Andrei Alexandrescu: https://youtu.be/va9I2qivBOA?t=1748 – Bob__ Apr 18 '23 at 20:34
  • This is well-defined. Why anyone would want to write a thing like that is beyond me, but you definitely can. – n. m. could be an AI Apr 18 '23 at 21:16
  • Why do you suppose that it wouldn’t be valid? It’s hard to explain an unspecified misconception. – Davis Herring Apr 19 '23 at 02:57
  • See [Template Argument Deduction](https://en.cppreference.com/w/cpp/language/template_argument_deduction). You are explicitly specifying the arguments for the 1st pack, and letting the compiler deduce the arguments for the 2nd pack – Remy Lebeau Apr 19 '23 at 08:15
  • @bob. Thank you for that reference. That clarifies it nicely. – Generic Name Apr 19 '23 at 16:52

0 Answers0