我想在编译时使用std::ratio
类型进行计算。我已经写了一个用于参数包的基本函数。但是,为了将ratios
保存在其他对象中,我将其放在参数包包装器中。如何解开包装好的参数包,以将其推入函数中?
我的代码如下:
#include <ratio>
#include <functional>
#include <initializer_list>
namespace cx {
// I need constexpr accumulate.
// However, the standard library currently doesn't provide it.
// I therefore just copied the code from
// https://en.cppreference.com/w/cpp/algorithm/accumulate
// and added the constexpr keyword.
template<class InputIt, class T, class BinaryOperation>
constexpr T accumulate(InputIt first, InputIt last, T init, BinaryOperation op)
{
for (; first != last; ++first) {
init = op(std::move(init), *first); // std::move since C++20
}
return init;
}
}
// wrapper type
template <class...T> struct wrapper { };
// helper to get the value out of the ratio type
template <class T>
struct get_val {
static constexpr auto value = double(T::num) / double(T::den);
};
// function for calculating the product of a vector type
template <class T>
constexpr auto product(T values) {
return cx::accumulate(std::begin(values),
std::end(values),
1,
std::multiplies<typename T::value_type>());
}
// my calculation (needs a parameter pack, can't the handle wrapper type)
template <class...T>
struct ratio_product
{
// this works by wrapping the Ts into an initializer list
// and using that for the calculation
static constexpr auto value =
product(std::initializer_list<double>{get_val<T>::value...});
};
//test
int main() {
//this works on a parameter pack (compiles)
static_assert(ratio_product<
std::ratio<5>, std::ratio<5>, std::ratio<4>
>::value == 100,"");
//this should work on a parameter pack wrapper (does not compile)
static_assert(ratio_product<
wrapper<
std::ratio<5>, std::ratio<5>, std::ratio<4>
>
>::value == 100,"");
}
答案 0 :(得分:2)
这是将参数包解包到任意模板中的一种可重用方法:
template <class Wrapper, template <class...> class Template>
struct unwrap;
template <class... Ts, template <class...> class Template>
struct unwrap<wrapper<Ts...>, Template> {
using type = Template<Ts...>;
};
产生以下static_assert
的内容,可以达到您的期望:
static_assert(
unwrap<
wrapper<std::ratio<5>, std::ratio<5>, std::ratio<4>>,
ratio_product
>::type::value == 100, "");
答案 1 :(得分:0)
我找到了解决方案。通过使用模板特化,可以从包装器中提取参数包:
template <class...T> struct ratio_product {
static constexpr auto value = product(std::initializer_list<double>{get_val<T>::value...});
};
template <class...T> struct ratio_product<wrapper<T...>> {
static constexpr auto value = ratio_product<T...>::value;
};