检查模板中 nullptr 的函数指针,了解任何类型的可调用对象
Check function pointer for nullptr in a template for any kind of callable
我创建了简单的包装器来捕获,报告和重新抛出异常(见下文(。它适用于函数、函数指针和std::function
对象,但由于检查nullptr
,无法针对 lambda 和函子进行编译。有没有办法尽可能简单地解决这个问题,以便包装器可用于任何类型的可调用对象?谢谢!
#include <functional>
template<typename Func, typename TRet, typename... Args>
TRet wrapper(Func func, TRet exit_code_on_error, Args... args) {
TRet exit_code = exit_code_on_error;
//if (func) // this condition does not compile for lambdas and functors
{
try {
exit_code = func(std::forward<Args>(args)...);
} catch(...) {
// report and possibly rethrow
//throw;
}
}
return exit_code;
}
int test1(double d) {
return (int)d;
}
int test2(std::function<int (double)> f, double d) {
return f(d);
}
struct TestFunctor {
int operator()(double d) {
return (int)d;
}
};
int main() {
// OK:
wrapper(test1, 1, 2.3);
wrapper(&test1, 1, 2.3);
auto p = test1;
wrapper(p, 1, 2.3);
p = nullptr;
wrapper(p, 1, 2.3);
wrapper(test2, 1, test1, 2.3);
// These lines cause the troubles:
wrapper([](double d){ return (int)d; }, 1, 2.3);
wrapper(TestFunctor(), 1, 2.3);
}
错误:
wrapper.hpp: error C2451: conditional expression of type 'Func' is illegal
with
[
Func=main::<lambda_1>
]
我们可以通过首先检查Func
是否是指针类型来解决此问题,如果是,则检查它是否为空指针。 那看起来像
template<typename Func, typename TRet, typename... Args>
TRet wrapper(Func func, TRet exit_code_on_error, Args... args) {
if constexpr(std::is_pointer_v<Func> ||
std::is_member_function_pointer_v<Func> ||
std::is_same_v<Func, std::function<TRet(Args...)>>) {
// this will only be compiled if Func is a pointer type or std::function
if (func == nullptr)
return exit_code_on_error;
}
try {
return func(std::forward<Args>(args)...);
} catch(...) {
// report and rethrow if needed
//throw;
}
return exit_code_on_error;
}
相关文章:
- 正在尝试了解输入验证循环
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 了解 GLM- openGL 中的相机转换
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- C++我需要了解在哪里使用指针和双指针
- 如何在不产生任何垃圾的情况下获得C中的像素
- 如何深入了解明显的腐败
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- C++映射有2个键,这样任何1个键都可以用来获取值
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 了解嵌套循环打印星号图案
- RtlCaptureStackBackTrace未捕获任何帧
- 链表c++插入,所有情况都已检查,但没有任何工作
- C++模板函数,用于比较任何无符号整数和有符号整数
- Arduino millis() - millis() 怎么能等于 0 以外的任何东西?
- 尝试摆脱任何堆内存分配
- 是否有任何C++功能可以对地图进行排序?
- 打印时有二叉树问题.用户输入不打印任何内容
- 检查模板中 nullptr 的函数指针,了解任何类型的可调用对象
- 了解任何体素图形c++库