简体   繁体   中英

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?

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?

template <class T>

T list<T>::getData(int i){

    if (i < iSize && i >= 0){

        return listData[i];

    } else {

        cout << "Does not exist";

    return {};

  }

}

//it works pretty well

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM