non type template parameter pack expansion

Viewed 114

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?

2 Answers

With the use of a helper variable.

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

Another alternative is to additionally define the first template parameter to facilitate formatting.

#include <iostream>

template<int... N> 
struct X {
  static void Check() { 
    if constexpr (sizeof...(N)) 
      [](auto first, auto... rest) {
        std::cout << first;
        ((std::cout << " " << rest), ...);
        std::cout << "\n";
      }(N...);
  }
};

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