【发布时间】:2018-08-04 16:21:48
【问题描述】:
我希望将三个函数合并在一起。
每个都将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();
}
}
任何建议将不胜感激!
【问题讨论】:
-
我感觉到一个模板函数的可能应用与可变模板参数。
标签: c++ c++11 templates variadic-templates std-function