【发布时间】:2018-08-08 10:41:40
【问题描述】:
我想在编译时使用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,"");
}
【问题讨论】:
标签: c++ templates variadic-templates compile-time