gpt4 book ai didi

c++ - 如何为我的数组选择更大的数据类型?

转载 作者:行者123 更新时间:2023-12-02 12:20:15 24 4
gpt4 key购买 nike

我的函数采用两个数组,它们存储具有原始数据类型的数据。

我想为我的结果数组选择更大的数据类型以防止数据丢失将值插入数组时。

例如:第一个数组存储 int,第二个数组存储 double。 result 数组应该有 double。

template<std::size_t length, typename A1, typename A2>
constexpr auto function(A1 array1, A2 array2){
//e.g array1 ints, array2 doubles
//do calculations and insert values into result array
std::array< ???, length> result{};
return array3;
}

最佳答案

std::common_type来救援。只要存在两种数组元素类型都可以转换为的类型,它就会为您提供该类型。因此,对于 intdoublestd::common_type 将为您提供 double。您可以将其用于您的数组,例如

std::array<std::common_type_t<A1::value_type, A2::value_type>, length> result{};

关于c++ - 如何为我的数组选择更大的数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59879761/

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