Liz Liz - 3 months ago 6
C++ Question

How to return a NULL from a templated method, without using a pointer

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?

Danke, auf wiedersehen

Answer

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