c++ - 根据函数参数数目调用不同的函数

浏览:41日期:2023-04-05

问题描述

我现在需要对矩阵进行操作,这些操作的过程都是类似的,只是其中的一个算子不同。这些算子有些是对每个元素操作,有些是对相邻之间的进行操作,我尝试用以下的方法去把算子和步骤分离开来,但是问题是对于参数个数不同的情况怎么处理?能不能编译时就确定好该调用的函数?

#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;}

问题解答

回答1:

恰好我也做过类似的矩阵库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来解决。

回答2:

把多个参数放到结构体里,用结构体指针当参数可行否?

回答3:

从你的代码上看有很多方案.f2的b是简单就可以拿到的,那可以 executor(std::bind(f2, _1, 2), m); 也可以

auto b = 3;auto f2_ = [&b](auto& v) { return f2(std::forward<decltype(v)>(v), b);};executor(f2_, m);

如果是其他的值,可以用std::enable_if去写executor的重载,原理就是用SFINAE原则.

相关文章: