I got a little problem with templates:
template <typename T>
T Func(){
std::string somestr = "";
// somestr = ...
if (somestr != ""){
return boost::lexical_cast<T>(somestr);
}
else{
T ret; // warning: "ret may be uninitialized in this function"
return ret;
}
}
If this function fails to get a result, I want to return a valid object, but as empty as possible. If I do it like above, I get the warning "ret may be uninitialized in this function". Try-Catch does not help to remove the warning..
Is there a way for this like the default
keyword in C#?
return default(T); // C#
Thanks!
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .
Java doesn't require a constructor when we create a class. However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors. This is called the default constructor.
You can just call default constructor with new operator (like this: new Test();) or this();. just Test() is forbidden because its not a method of class. Show activity on this post. In Java, the default constructor is the no-argument constructor that's implicitly provided by the compiler.
The simple answer is yes. It has a default constructor. Note: struct and class are identical (apart from the default state of the accesses specifiers).
ret
might be uninitialized because T
might be a POD type or another type that has no user-declared constructors.
You can invoke the default constructor (and value-initialize any POD type object) like so:
T ret = T();
return ret;
or, more succinctly,
return T();
This assumes that T
is default-constructible. If you may need to instantiate this function with a type that is not default constructible, you can take the "default" case as a parameter. For example,
template <typename T>
T Func(const T& default_value = T())
{
// ...
}
This will allow you still to call Func()
for types that are default constructible, but also to explicitly provide a value to return for types that are not.
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