In C# I know you can use the default keyword to assign default values as 0 to value types and null to reference types and for struct types individual members are assigned accordingly. To my knowledge there are no default values in C++. What approach would you take to get the same functionality as the default keyword for Generics while programming in C++?
Assuming the type is default-constructible, you can use value initialization. For example,
template <typename T>
T get()
{
return T(); // returns a value-initialized object of type T
}
If the type is not default-constructible, typically you need to provide a default to use. For example,
template <typename T>
T get(const T& default_value = T())
{
return default_value;
}
This function can be called with no argument if the type is default-constructible. For other types, you can provide a value to be returned.
C++ doesn't have the default
keyword, because it doesn't have the distinction between reference and value types. In C++, all types are what C# would consider value types, and if they're default constructible (as built-in types, POD structs and class types with default constructors are), they are initialized using value initialization (the default constructor syntax), as James McNellis showed: (and shamelessly copied here)
template <typename T>
T get()
{
return T(); // returns a value-initialized object of type T
}
if T
has a default constructor, it is invoked. If it has no constructors, everything is initialized to zero/null.
And if the type is not default constructible, there is no default value the object could be given.
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