gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:24:19 24 4
gpt4 key购买 nike

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

每个都将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com