【问题标题】:non type template parameter pack expansion [duplicate]非类型模板参数包扩展
【发布时间】:2021-12-28 07:05:13
【问题描述】:

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

例子:


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

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

【问题讨论】:

    标签: c++ c++17 fold-expression parameter-pack


    【解决方案1】:

    使用辅助变量。

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

    【讨论】:

    • 好的,一般来说答案是,我们没有可以处理它的折叠表达式,因此我们需要扩展为一个单独的单个 couts 语句的列表。在&lt;&lt; 不会返回输入ostream 或ostream 将使用iomanip 运算符修改的情况下,它也将不起作用。谢谢!
    • @Klaus stream&amp; = std::cout; ?
    • @Klaus 你可以从字符串流中获得一个临时字符串,然后只用一个 ostream 输出它
    • @Klaus this is 是一个折叠表达式,, 作为运算符。如果您的流不返回自身,您可以进一步拆分它:((std::cout &lt;&lt; (count++? " " : ""), std::cout &lt;&lt; N), ...)
    • 我更喜欢无分支版本:const char* sep = ""; (((std::cout &lt;&lt; sep &lt;&lt; Is), sep = " "), ...);.
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      相关资源
      最近更新 更多