开发者

C++ Template Default Constructor

I g开发者_开发百科ot 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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜