c++ 访问另一个别名(带有折叠表达式的参数包)中的单个别名

4nkexdtk  于 2023-04-01  发布在  其他
关注(0)|答案(1)|浏览(84)

给定这些类型:

template<Ratio r, Symbol s>
struct base_unit {
    using ratio = r;
    using symbol = s;
};

template <BaseUnit... baseUnits>
struct derived_unit {
    using units = std::tuple<baseUnits...>;
};

例如,如果我有一个如下类型:

template <typename T>
struct Computations {
    using collection_ratios = /* */
    static constexpr ratios_product = /* */
}

我想知道我该如何:

  • 将给定derived_unit的所有比率存储在容器中,如std::array〈T,N〉,并使用折叠表达式(collection_ratios)
  • 存储derived_unitunits成员中的每个元素相乘的结果,并将其存储在具有折叠表达式(ratios_product)的变量中

编辑:
其中Tderived_unit的特殊化,例如:

struct MetersPerSecond :
   public speed,
   public derived_unit<         
        base_unit<Kilo, m>,
        base_unit<Root, s>
   >
{};

编辑二:

template <typename T>
concept RatioV = (std::is_integral_v<T> || std::is_floating_point_v<T>)
    && !std::is_same_v<T, char>;

consteval double getFactor(double base, double exponent);

template <RatioV T = short, T Base = 10, T Exponent = 0>
struct ratio {
    static constexpr T base = Base;
    static constexpr T exponent = Exponent;
    static constexpr T value = getFactor(base, exponent);
};

consteval double getFactor(double base, double exponent) {
    double result = 1;
    for (int i = 0; i < exponent; i++)
        result *= base;
    return result;
}

using Yocto = ratio<short, 10, -24>;
using Zepto = ratio<short, 10, -21>;
using Atto = ratio<short, 10, -18>;
using Femto = ratio<short, 10, -15>;
using Pico = ratio<short, 10, -12>;
using Nano = ratio<short, 10, -9>;
using Micro = ratio<short, 10, -6>;
using Milli = ratio<short, 10, -3>;
using Centi = ratio<short, 10, -2>;
using Deci = ratio<short, 10, -1>;
using Root = ratio<short, 10, 0>;
using Deca = ratio<short, 10, 1>;
using Hecto = ratio<short, 10, 2>;
using Kilo = ratio<short, 10, 3>;
using Mega = ratio<short, 10, 6>;
using Giga = ratio<short, 10, 9>;
using Tera = ratio<short, 10, 12>;
using Peta = ratio<short, 10, 15>;
using Exa = ratio<short, 10, 18>;
using Zetta = ratio<short, 10, 21>;
using Yotta = ratio<short, 10, 24>;
rwqw0loc

rwqw0loc1#

这是你要找的吗?
它所做的就是将比率类型的列表获取到collection_ratios中。并使用该列表,将所有静态value的相乘到ratios_product中。

template<typename Tuple>
struct ratios;

template<typename... Ts>
struct ratios<std::tuple<Ts...>> {
    using type = std::tuple<typename Ts::ratio...>;
};

template <typename Tuple>
struct ratios_product_impl;

template<typename... Ts>
struct ratios_product_impl<std::tuple<Ts...>>
{
    static constexpr auto value = (1 * ... * Ts::value);
};

template <typename T>
struct Computations {
    using collection_ratios = typename ratios<typename T::units>::type;

    // Calculates the product of all ratio values.
    static constexpr auto ratios_product = ratios_product_impl<collection_ratios>::value;
};

#include <iostream>

int main() {
    Computations<MetersPerSecond> c;
    std::cout << c.ratios_product; // Prints 10000 for MetersPerSecond.
    return 0;
}

相关问题