非类型模板参数包扩展

Kla*_*aus 5 c++ fold-expression c++17 parameter-pack

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

例子:


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();
}
Run Code Online (Sandbox Code Playgroud)

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

bip*_*pll 4

使用辅助变量。

std::size_t count{};
((std::cout << (count++? " " : "") << N), ...);
Run Code Online (Sandbox Code Playgroud)