【发布时间】:2023-04-05 08:18:01
【问题描述】:
假设我有 2 个表示两个多项式系数的元组,我该如何计算乘法系数。 我想使用模板来完成这个。
mul_scalar() 将元组的值与标量相乘。
我正在尝试使用此函数扩展到多项式情况。通过迭代一个元组并使用mul_scalar()
#include <tuple>
#include <utility>
#include <iostream>
template<std::size_t I = 0, typename T, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
mul_scalar(const T& lhs, const std::tuple<Tp...> rhs ) // Unused arguments are given no names.
{ }
template<std::size_t I = 0, typename T, typename... Tp>
inline typename std::enable_if<I < sizeof...(Tp), void>::type
mul_scalar(const T& lhs, const std::tuple<Tp...> rhs)
{
std::cout << (std::get<I>(rhs))*lhs << " ";
mul_scalar<I + 1, T, Tp...>(lhs, rhs);
}
template <std::size_t I = 0, template <typename ...> class Tup1, template <typename ...> class Tup2, typename ...A, typename ...B>
inline typename std::enable_if<I < sizeof...(A), void>::type
mul_poly(const Tup1<A...>& lhs, const Tup2<B...> rhs)
{
mul_scalar(std::get<I>(lhs), rhs);
//mul_poly(lhs, rhs); with I = I + 1
// However I can't figure how to give other template args
}
int main(){
auto poly_1 = std::make_tuple(2,1);
auto poly_2 = std::make_tuple(3,4,5);
mul_scalar(3,poly_1);
std::cout << "\n";
// Expected output 6 8 10 3 4 5
mul_poly(poly_1, poly_2);
}
【问题讨论】:
-
严格来说 C++11 或 C++14/C++17 可以吗?
-
更喜欢 C++11。但是,如果您也能告诉我其他方法,那就太好了。
-
通过不同的方法示例改进了答案;希望这会有所帮助。
标签: c++ c++11 templates variadic-templates template-meta-programming