我试图执行矩阵求幂,但我不想复制/粘贴我的指数函数,而宁愿使用类模板。问题是对于增强矩阵来说,为了使矩阵相乘,可以使用prod
函数(而不是operator*
)。如何将boost矩阵prod()函数作为乘法函数传递?
似乎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
由于一吨。给你upvote,但我最终独立使用了与dhavenith相同的解决方案,所以我给了他支票。尽管他对返回类型做出了假设,但考虑到您提供的更一般包装的复杂性,我认为这是可以原谅的。其他任何人都觉得有时候会提高方式来解决问题? – Brian 2012-02-02 15:13:27
和upvote查找'matrix_matrix_binary_traits'。 – dhavenith 2012-02-03 15:50:53