如何将具有不同参数的std :: function传递给同一个函数

Gri*_*ort 9 c++ templates variadic-templates c++11 std-function

我有三个功能,我想合并在一起.

每个std::function参数都作为第一个参数,然后在try/ catch块中执行.

问题是,有三种不同类型的功能.没有参数的函数,带有一个整数参数的函数和带有两个整数参数的函数.具有整数参数的参数也具有通过原始函数传递的相应参数.

可以看出,每个函数几乎都是相同的,所以如果我可以将它们合并在一起会很好.但是,我不确定无论如何设置一个可以接收任何形式的参数,std::function并且还依赖于它已经提供了相应的数据来使用.

以下是功能:

void run_callback(std::function<void()>& func) {
    try {
        func();
    } catch(const std::exception& ex) {
        print_callback_error(ex.what());
    } catch(const std::string& ex) {
        print_callback_error(ex.c_str());
    } catch(...) {
        print_callback_error();
    }
}

void run_callback_int(std::function<void(int)>& func, int data) {
    try {
        func(data);
    } catch(const std::exception& ex) {
        print_callback_error(ex.what());
    } catch(const std::string& ex) {
        print_callback_error(ex.c_str());
    } catch(...) {
        print_callback_error();
    }
}

void run_callback_intint(std::function<void(int, int)>& func, int data1, int data2) {
    try {
        func(data1, data2);
    } catch(const std::exception& ex) {
        print_callback_error(ex.what());
    } catch(const std::string& ex) {
        print_callback_error(ex.c_str());
    } catch(...) {
        print_callback_error();
    }
}
Run Code Online (Sandbox Code Playgroud)

任何建议将不胜感激!

max*_*x66 11

它似乎适用于可变参数模板.

就像是:

template <typename ... Args>
void run_callback(std::function<void(Args...)> const & func, Args ... as) {
    try {
        func(as...);
    } catch(const std::exception& ex) {
        print_callback_error(ex.what());
    } catch(const std::string& ex) {
        print_callback_error(ex.c_str());
    } catch(...) {
        print_callback_error();
    }
}
Run Code Online (Sandbox Code Playgroud)

或者(可能更好地管理可能的转发)

template <typename ... FArgs, typename ... Args>
void run_callback(std::function<void(FArgs...)> const & func,
                  Args && ... as) {
    try {
        func(std::forward<Args>(as)...);
    } catch(const std::exception& ex) {
        print_callback_error(ex.what());
    } catch(const std::string& ex) {
        print_callback_error(ex.c_str());
    } catch(...) {
        print_callback_error();
    }
}
Run Code Online (Sandbox Code Playgroud)