I have some code that looks like this:
template <class T>
T foo(T a) {
if (a) {
// do somethin', returns object of type T
} else {
return NULL;
}
}
But of course it won't compile since NULL is not of type T. Someone suggested this solution to me but I don't like it:
template <class T>
T* foo(T a) {
if (a) {
// do somethin', returns object of type T*
} else {
return nullptr;
}
}
I am wondering how to make this function able to return a NULL value if possible without the use of a pointer?
In C++17, you will be able to use std::optional<T>
. And you could do something like this:
template <class T>
std::optional<T> foo(T a) {
if (a) {
// do somethin', returns object of type T
return std::make_optional(/*Anything that constructs `T`*/);
} else {
return {};
}
}
And on the receiving end, you can test for the value being there:
auto my_val = foo(obj);
if(my_val){
/* :-) ....knock yourself out! */
}
else{
/* :-( ....we didn't find the value */
}
For now,
You can use Boost.Optional.
Or, if you are using a very recent compiler, you may be able to access it from std::experimental::optional
.
Or, if you do not want to use Boost and its dependencies, you can simply grab this tiny header (a working implementation of optional from one of the proposers of optional
into the C++ standard)... It's header only, so, you only need to download/copy that single header file and #include
it.
Another cool thing with C++17 is that testing for the value will now be as simple as:
if(auto my_val = foo(obj); my_val){
// ....knock yourself out!
}
You can see more of C++17 features here: What are the new features in C++17?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With