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();
This is very much more succinct:
return {};
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.
How about typedef
?
class VeryVeryVeryLongTypeName;
typedef class VeryVeryVeryLongTypeName S;
And then use S
.
See HERE
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.
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