【问题标题】:std::initializer_list usage in variadic template function可变参数模板函数中的 std::initializer_list 用法
【发布时间】:2020-08-25 05:17:23
【问题描述】:

我不明白下面的代码 sn-p 是如何工作的。尤其是std::initializer_list的用法。

template<typename ... T>
auto sum(T ... t)
{
   typename std::common_type<T...>::type result{};
   std::initializer_list<int>{ (result += t, 0) ... };

   return result;
}

【问题讨论】:

    标签: c++ c++11 templates c++14 variadic-templates


    【解决方案1】:
    template<typename ... T>
    auto sum(T ... t)
    {
       //getting the common type of the args in t and initialize a new var
       //called result using default constructor
       typename std::common_type<T...>::type result{};
    
      //(result += t, 0) ... this just sum the result and the next arg in the
      //parameter pack and then returns zero, hence the initializer_list will be filled 
      //only by zeros and at the end result will hold the sum of the args 
       std::initializer_list<int>{ (result += t, 0) ... };
    
       return result;
    }
    

    相当于

    template<typename ... T>
    auto sum(T ... t)
    {
        return (t+...);
    }
    

    【讨论】:

    • 让我难过的是,我们在 C++ 中需要像这样的骇客来快速导航参数包。这表现力如何?!
    • initializer_list 如何在括号内递归执行?
    • @MustafaCOKER 它没有。这个(result += t, 0) ... 在括号内返回0,0,0,..。比如你写{0,0,0,...}
    • 大家好,对不起,我无法理解result += t 之后零的作用。而且,编译器不关心这个参数。如果我更改了它(result += t, 2 或 result += t, false),结果保持不变。如果我删除这个参数,结果仍然相同,但编译器会发出警告。
    • 我明白了。非常非常非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 2013-06-14
    • 2019-01-18
    • 2019-04-30
    • 1970-01-01
    • 2017-08-07
    • 2011-01-22
    相关资源
    最近更新 更多