Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to elegantly return an object that is default-initialized?

I have a class like below:

class VeryVeryVeryLongTypeName
{
    bool is_ok;

    VeryVeryVeryLongTypeName() : is_ok(false) {}
};

VeryVeryVeryLongTypeName f()
{
    VeryVeryVeryLongTypeName v;

    ... // Doing something

    if (condition_1 is true)
    {
        return v;
    }
    else
    {
        return VeryVeryVeryLongTypeName();
    }

    ... // Doing something

    if (condition_2 is true)
    {
        return v;
    }
    else
    {
        return VeryVeryVeryLongTypeName();
    }    
}

I think the statement return VeryVeryVeryLongTypeName(); is very tedious and ugly, so, my question is:

How to elegantly return an object that is default-initialized?

or in other words:

Is it a good idea to add a feature into the C++ standard to make the following statement is legal?

return default; // instead of return VeryVeryVeryLongTypeName();
like image 554
xmllmx Avatar asked Sep 14 '13 06:09

xmllmx


4 Answers

This is very much more succinct:

   return {};
like image 162
goji Avatar answered Sep 30 '22 21:09

goji


You can use this class whose instance will implicitly convert into an instance of desired type automatically. This should work even if the default constructor is marked explicit or if you're still using C++03. For C++11, the accepted answer is succinct and better.

const struct default_t
{
     template<typename T>
     operator T() const {   return T{}; }
}default_{};

And use it as:

VeryVeryVeryLongTypeName f()
{
     //...
     return default_;
}

WithExplicitConstructor_VeryVeryVeryLongTypeName g()
{
     //...
     return default_;
}

Online Demo.

You can use this solution everywhere, even in templates:

template<typename T>
typename father::template daughter<T>::grand_son_type h()
{
     //...
     return default_;
}

Hope that helps.

like image 39
Nawaz Avatar answered Sep 30 '22 20:09

Nawaz


How about typedef ?

class VeryVeryVeryLongTypeName;
typedef class VeryVeryVeryLongTypeName S;

And then use S.

See HERE

like image 23
P0W Avatar answered Sep 30 '22 19:09

P0W


As others have pointed out, you can rely on defining a type alias. In C++11 you can use the notation

using SnappyName = VeryVeryVeryLongTypeName;

and then use SnappyName anywhere you want to.

Remember that you will need to come back to your code, say, six months from now. Use an approach which will help you (or your collaborators) understand unequivocally what you meant. Remember: code is written once and read many times. Code for later readability, not for present keystroke savings.

like image 27
Escualo Avatar answered Sep 30 '22 20:09

Escualo