我正在尝试执行矩阵求幂,但我不想复制/粘贴我的求幂函数,而宁愿使用类模板。问题是对于 boost 矩阵,要乘以矩阵,您使用prod
函数(而不是operator*
)。
似乎 g++ 无法找出我想要使用的模板。我用下面的代码得到的错误是
41:37: error: no matching function for call to 'my_pow(boost::numeric::ublas::matrix<int>&, int, <unresolved overloaded function type>)'
这是代码:
#include <iostream>
using namespace std;
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
typedef long long int64;
template <class T, class M> T my_pow(T b, int64 e, M mult)
{
if (e == 1) return b;
if (e % 2 == 1) return mult(b, my_pow(b, e - 1, mult));
T tmp = my_pow(b, e / 2, mult);
return mult(tmp, tmp);
}
template <class T> T my_pow(T b, int64 e) { return my_pow(b, e, multiplies<T>()); }
int main()
{
using namespace boost::numeric::ublas;
matrix<int> m(3, 3);
for (unsigned i = 0; i < m.size1(); ++i)
for (unsigned j = 0; j < m.size2(); ++j)
m(i, j) = 3 * i + j;
std::cout << m << std::endl;
std::cout << my_pow(m, 2, prod) << std::endl;
}
有没有办法将 prod() 传递给 my_pow 以便模板解析?谢谢。
如果不清楚:b 是底数,e 是指数,my_pow 是计算 b^e