gpt4 book ai didi

c++ - C++中的评估顺序初始化数组

转载 作者:可可西里 更新时间:2023-11-01 16:35:34 27 4
gpt4 key购买 nike

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

看这个例子:

#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");

}

问:数组初始化的求值顺序是顺序的还是任意的(或者实现定义的,未定义的行为)?

如果 make_vector 错误,我该如何解决?

最佳答案

它们是按顺序计算的。 C++11 § 8.5.4 [dcl.init.list] 第 4 段:

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.

鉴于 vector 有一个 initializer_list 构造函数,您可以将您的函数简化为:

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

而且不必担心神秘的初始化语义;)

关于c++ - C++中的评估顺序初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20186084/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com