How to return a NULL from a templated method, without using 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?

Tags:

C++