search

Home  >  Q&A  >  body text

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;
}
伊谢尔伦伊谢尔伦2772 days ago608

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 15:02:27

    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

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

    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 removing constexpr, you may have to use std::enable_if to solve.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 15:02:27

    Is it possible to put multiple parameters into a structure and use structure pointers as parameters?

    reply
    0
  • 黄舟

    黄舟2017-04-17 15:02:27

    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

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

    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.

    reply
    0
  • Cancelreply