Search code examples
c++c++17fold-expressionparameter-pack

non type template parameter pack expansion


I simply would print out a non type template parameter pack. But I can't find a valid expansion if I want to have spaces in between the elements.

Example:


template < int ... N > 
struct X
{
    static void Check() { 
        // this will become std::cout << ( 1 << 2 ) << std::endl; -> prints "4"
        std::cout << "X" << (N << ...) <<  std::endl; 

        // this will become: ((std::cout << 1 ) << 2 ) << std::endl; -> prints "12"
        (std::cout << ... << N) << std::endl;

        // this becomes: (( std::cout << " " << 1 ) << 2 ) -> prints " 12"
        (std::cout << " " << ... << N) << std::endl;

        // the following is not allowed
        (std::cout << ... << " " << N) << std::endl;

        // also this one is not compiling
        (std::cout << ... << N << " ") << std::endl;
    }   
};

int main()
{
    X<1,2>::Check();
}

Is there any chance to expand the parameter pack to print the elements with space in between without using a helper function?


Solution

  • With the use of a helper variable.

    std::size_t count{};
    ((std::cout << (count++? " " : "") << N), ...);