评估顺序初始化数组在c ++ [英] evaluation order initialization array in c++

查看:149
本文介绍了评估顺序初始化数组在c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢c ++ 11可变参数模板,所以我经常写一些小代码。

I like c++11 variadic templates, so I often write some little codes with it.

查看这个例子:

#include <cstdio>
#include <type_traits>
#include <vector>

template< typename ... T >
auto make_vector(T ... t ) -> std::vector< typename std::common_type<T...>::type >
{
    std::vector< typename  std::common_type<T...>::type > v;
    v.reserve( sizeof...(T) );

    using list = int[];
    (void)list{ 0, ( (void)v.push_back(std::move(t)) ,0)... };
    //                |/ / / /
    //                --------
    //                 \-- How are evaluated v.push_back()s, sequentially or arbitrary ?
    return v;
}

int main()
{
    auto v = make_vector(2, 3.0, 'a', 7UL );

    for(auto e : v )
      printf("%.2lf ", e);

    printf("\n");

}

Q:

如果 make_vector 错误,我修复了它?

If make_vector is wrong, how me fix its?

推荐答案

C ++ 11§8.5.4 [dcl.init.list]第4段:

They are evaluated sequentially. C++11 § 8.5.4 [dcl.init.list] paragraph 4:


时, initializer-clause (包括pack
扩展(14.5.3)的任何结果)都在 braced-init- 。

Within the initializer-list of a braced-init-list, the initializer-clauses, including any that result from pack expansions (14.5.3), are evaluated in the order in which they appear.

由于向量 initializer_list 构造函数,您可以将函数简化为:

Given that vector has an initializer_list constructor, you could simplify your function to:

template <typename ... T>
auto make_vector(T ... t) ->
  std::vector< typename std::common_type<T...>::type >
{
  return { static_cast<typename std::common_type<T...>::type>(t)... };
}

,而不必担心奥术初始化语义;)

and not have to worry about arcane initialization semantics ;)

这篇关于评估顺序初始化数组在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆