我找到了一个非常简单的解决方案,只有一个可变参数函数:
#include <iostream>
#include <array>
#include <type_traits>
template<typename Type, typename OtherType, std::size_t Size, typename... Types, class = typename std::enable_if<sizeof...(Types) != Size>::type>
constexpr std::array<Type, Size> convert(const std::array<OtherType, Size> source, const Types... data);
template<typename Type, typename OtherType, std::size_t Size, typename... Types, class = typename std::enable_if<sizeof...(Types) == Size>::type, class = void>
constexpr std::array<Type, Size> convert(const std::array<OtherType, Size> source, const Types... data);
template<typename Type, typename OtherType, std::size_t Size, typename... Types, class>
constexpr std::array<Type, Size> convert(const std::array<OtherType, Size> source, const Types... data)
{
return convert<Type>(source, data..., static_cast<const Type>(source[sizeof...(data)]));
}
template<typename Type, typename OtherType, std::size_t Size, typename... Types, class, class>
constexpr std::array<Type, Size> convert(const std::array<OtherType, Size> source, const Types... data)
{
return std::array<Type, Size>{{data...}};
}
int main()
{
static constexpr std::array<double, 3> darray{{1., 2., 3.}};
static constexpr std::array<int, 3> iarray = convert<int>(darray);
std::cout<<(std::integral_constant<int, iarray[2]>())<<std::endl;
return 0;
}