我的函数采用两个数组,它们存储具有原始数据类型的数据。
我想为我的result数组选择更大的数据类型,以防止在将值插入数组时丢失数据。
例如:第一个数组存储整数和第二个双精度。该result阵列应该有一倍。
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;
}
Run Code Online (Sandbox Code Playgroud)
std::common_type到救援。只要存在两种数组元素类型都可以转换为的类型,它就会为您提供该类型。所以对于一个int和double,std::common_type会给你double。您可以将其用于您的阵列,例如
std::array<std::common_type_t<A1::value_type, A2::value_type>, length> result{};
Run Code Online (Sandbox Code Playgroud)