I'm finding myself doing a lot of
void doSomethingCool(CoolObject* coolObject) {
if (coolObject == nullptr) {
return;
}
// now _actually_ do something cool
}
I thought about macros, but it felt a bit gross...
// plus some other templating for other return types, but besides the point
#define RETURN_IF_NULL(nullable) if (nullable == null) { return; }
void doSomethingCool(CoolObject* coolObject) {
RETURN_IF_NULL(coolObject)
// now _actually_ do something cool
}
It would be cool to have something like std::return_if_null<T>
, like this
#include <early_return>
void doSomethingCool(CoolObject* coolObject) {
std::return_if_null(coolObject);
// now _actually_ do something cool
}
I don't think this is possible with C++ as it is now, but would be keen to hear if you think this could work, or if you think it would be an interesting language feature.
Edit, full context, what I would looove to see is something like this.
template <typename T, typename ReturnType>
std::early_return<ReturnType> return_if_null(T* ptr, ReturnType defaultValue = {}) {
static_assert(std::is_default_constructible<T>());
if (ptr == nullptr) {
return std::early_return::abort{defaultValue};
}
return std::early_return::continue;
}
is
return_if_null(T* ptr)
possible?
No.
I thought about macro
Ok, that is possible. But don't.
It's somewhat unclear why you want this, but if you're exploring different styles, you can write the function like this:
void doSomethingCool(CoolObject* coolObject) {
if (coolObject) {
// now _actually_ do something cool
}
}
But it's of course a matter of taste.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.