views:

167

answers:

1

Hi there!

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!

+20  A: 

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.

James McNellis
Thanks. Perfect.
opatut
Very good answer James.