应用可变函数的矩阵元素循环 [英] Loop over matrix elements applying variable function
问题描述
在我的矩阵类中有太多的实例
In my matrix class there are too many instances of
for(size_t i = 1 ; i <= rows ; i++){
for(size_t j = 1 ; i <= cols ;j++){
//Do something
}
}
记住DRY原则,我想知道是否可以
Keeping in mind the DRY principle , I was wondering whether I could
matrix<T>::loopApply(T (*fn) (T a)){ // changed T to T a
for(size_t i = 1 ; i <= rows ; i++){
for(size_t j = 1 ; i <= cols ;j++){
_matrix[(i-1)*_rows + (j-1)] = fn(a) // changed T to a
}
}
}
当我想循环并应用一些东西到矩阵我只需要调用loopApply(fn)
So that when I want to loop over and apply something to the matrix I just have to call loopApply(fn)
有什么办法吗?或者有更好的方法来做到这一点吗?
谢谢。
Is there any way to do this ? Or is there a better approach to do this ?
Thank You.
UPDATE
我正在寻找一个一般的方法来做到这一点。所以fn不必取一个参数等。我听说过变量参数,但我不明白他们是如何工作,或者如果他们适合这项工作。
UPDATE I am looking for a general way to do this. So that fn does not have to take a single parameter etc. I have heard about variadic parameters , but I could not understand how they work , or if they are suited for the job.
最小代码:
// in matrix.h
template <class T>
class matrix
{
public:
...
private:
...
std::vector<T> _matrix;
void loopApply(T (*fn) (T) );
}
#include "matrix.tpp"
//in matrix.tpp
template <class T> // Template to template // Pointed out in comment
// loopApply as written above
推荐答案
它看起来像
#include <iostream>
struct A
{
enum { N = 10 };
int a[N][N];
template <typename Fn, typename ...Args>
void method( Fn fn, Args...args )
{
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ ) a[i][j] = fn( args... );
}
}
};
int main()
{
return 0;
}
这篇关于应用可变函数的矩阵元素循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!