我现在需要对矩阵进行操作,这些操作的过程都是类似的,只是其中的一个算子不同。这些算子有些是对每个元素操作,有些是对相邻之间的进行操作,我尝试用以下的方法去把算子和步骤分离开来,但是问题是对于参数个数不同的情况怎么处理?能不能编译时就确定好该调用的函数?
#include <vector>
using namespace std;
template <typename OPER, typename T>
void executor(OPER op, vector<vector<T>>& m)
{
//--- pre processing
//...
//---
T last = T();
for (auto& v : m){
for (auto& a : v){
// if(varnum == 1)
op(a);
//if(varnum == 2)
//op(a, last); // fail
last = a;
}
}
//--- post processing
//...
//---
}
void f1(float& a)
{
a *= 2;
}
void f2(float& a, float b) // fail 需要两个参数
{
a -= b;
}
int main()
{
vector<vector<float>> m;
executor(f1, m);
//executor(f2, m); // fail
return 0;
}
I happen to have made a similar matrix library https://github.com/codehz/mat...
I have also encountered similar problems, although my needs are not the former and the latter, but The simple difference in parameters
The solution I adopted is to automatically determine it through the parameter list of the callback function - simplified as follows
The code of
function_traits
is used here to obtain function-related information during compilation.if constexpr
is a feature of C++17. If the compilation fails after removingconstexpr
, you may have to usestd::enable_if
to solve.Is it possible to put multiple parameters into a structure and use structure pointers as parameters?
Judging from your code, there are many solutions.
The b of f2 is easy to get, so you can
executor(std::bind(f2, _1, 2), m);
or
If it is other values, you can use std::enable_if to write the overload of the executor. The principle is to use the SFINAE principle.