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

标签 c++ c++11 templates variadic-templates std-function

我希望将三个功能合并在一起。

每个都将 std::function 作为第一个参数,然后在 try/catch block 中执行它。

问题是,存在三种不同类型的函数。不带参数的函数、带一个整数参数的函数和带两个整数参数的函数。整型参数的也有相应的参数通过原函数传递。

如您所见,每个功能几乎相同,所以如果我能将它们合并在一起就好了。但是,我不确定是否要设置一个可以接收任何形式的 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();
    }
}

如有任何建议,我们将不胜感激!

最佳答案

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

类似于:

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

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

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

关于c++ - 如何将具有不同参数的 std::function 传递给同一函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48967706/

相关文章:

c++输出流不适用于模板和 namespace

c++ - 如何从字符串中每行输出一个单词

c++ - "candidate template ignored: substitution failure:"编译错误?

c++ - 如何避免调用 vector 中元素的复制构造函数

c++ - 检查元素是 std::vector 中的第一个还是最后一个

c++ - 模板函数多态性

c++ - Visual C++ 编译器允许从属名称作为没有 "typename"的类型?

c++ - 是否可以仅使用 OpenGL 确定默认帧缓冲区的大小?

c++ - std::async 在 Visual Studio 2013 和 2015 之间的不同行为

c++ - 如何将 int 映射到 C/C++ 中的相应字符串