非类型模板参数包扩展

non type template parameter pack expansion

我只是打印出一个非类型模板参数包。但是如果我想在元素之间有 spaces,我找不到有效的扩展。

示例:


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();
}

是否有机会在不使用辅助函数的情况下扩展参数包以打印带有 space 的元素?

使用辅助变量。

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

另一种方法是另外定义第一个模板参数以方便格式化。

#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();
}