Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Template Default Constructor

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!

like image 995
opatut Avatar asked Aug 10 '10 01:08

opatut


People also ask

What does a default constructor do?

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() .

Do I need a default constructor?

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.

How do you call a 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.

Do structs have default constructors?

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).


1 Answers

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.

like image 69
James McNellis Avatar answered Sep 30 '22 12:09

James McNellis