gpt4 book ai didi

c++ - 如何在C++模板元编程中返回不止一种类型?

转载 作者:行者123 更新时间:2023-12-02 10:17:48 27 4
gpt4 key购买 nike

我有一个简单的模板元程序,可以将许多std::ratio转换为尽可能少的ratio。如果没有溢出(并且确实如此),则必须返回1 ratio;如果有溢出,则必须返回2或更多。有可能达到目标吗?

template<class R, class ...Rs> struct unite_ratio;

template<intmax_t Num, intmax_t Den>
struct unite_ratio<std::ratio<Num, Den>>
{
using type = std::ratio<Num, Den>;
};

template<
intmax_t Num1, intmax_t Den1,
intmax_t Num2, intmax_t Den2,
class ...Rs
> struct unite_ratio<std::ratio<Num1, Den1>, std::ratio<Num2, Den2>, Rs...>
{
// here might be an overflow
static constexpr intmax_t num =
std::__static_sign<Den1>::value * std::__static_sign<Den2>::value *
(Num1 / std::__static_gcd<Num1, Den2>::value) *
(Num2 / std::__static_gcd<Num2, Den1>::value);

// Here might be an overflow as well
static constexpr intmax_t den =
(std::__static_abs<Den1>::value / std::__static_gcd<Num2, Den1>::value) *
(std::__static_abs<Den2>::value / std::__static_gcd<Num1, Den2>::value);

// returns only one type
using type = unite_ratio<std::ratio<num, den>, Rs...>;
};

最佳答案

How to return more than one type in C++ template meta-programming?



带有类型列表。它只是一个模板类,其可变参数的模板参数列表为类型列表:
template<class...T>
struct types{};

关于c++ - 如何在C++模板元编程中返回不止一种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61350499/

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