c++ - 根据函数参数数目调用不同的函数
本文介绍了c++ - 根据函数参数数目调用不同的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我现在需要对矩阵进行操作,这些操作的过程都是类似的,只是其中的一个算子不同。这些算子有些是对每个元素操作,有些是对相邻之间的进行操作,我尝试用以下的方法去把算子和步骤分离开来,但是问题是对于参数个数不同的情况怎么处理?能不能编译时就确定好该调用的函数?
#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;
}
解决方案
恰好我也做过类似的矩阵库https://github.com/codehz/mat...
也遇到过类似的问题,虽然我的需求不是前一个和后一个,而是单纯的参数的不同
我采取的解决方案是,通过回调函数的参数列表自动决定——简化如下
template <typename F>
real_t &for_each(F f) const
{
for(std::size_t row = 0; row < Rows; row++)
for(std::size_t col = 0; col < Cols; col++)
if constexpr (function_traits<F>::arity == 1) f(data[row][col]);
else if constexpr (function_traits<F>::arity == 0) f();
else if constexpr (function_traits<F>::arity == 3) f(data[row][col], row, col);
else throw "for_each(const) failed";
return static_cast<real_t &>(*this);
}
其中function_traits
的代码在这里用于在编译期得到函数的相关信息if constexpr
是C++17的特性,如果去除constexpr
后通不过编译,可能得使用std::enable_if
来解决。
这篇关于c++ - 根据函数参数数目调用不同的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文