Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

.net - What is the C++/CLI equivalent to C#'s default(T)?

I'm working with some C++/CLI code (new syntax) and am trying to declare a generic type and want to set a member variable to it's default.

In C#:

class Class<T>
{ 
    T member = default(T);
}

What's the equivalent in CLI?

generic<typename T> public ref class Class 
{
public:
    Class() : member(default(T))  // <-- no worky
    {
    }    
private:
        T member;
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Interestingly enough the syntax makes it looks like this: T(). It does require the addition of a copy constructor.

generic<typename T> 
    public ref class Class 
{
public:
    Class() : member(T())  
    {
    } 

    Class(Class^ c)
    {
        member = c->member;
    }

private:
    T member;
};

Edit DOH This works too (been in C# land for so long I forgot that NULL and 0 are the same thing in C++, hence no need for different value and reference type default values):

generic<typename T> 
    public ref class Class 
{
public:
    Class() : member(0)  
    {
    } 

    Class(Class^ c)
    {
        member = c->member;
    }

private:
    T member;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...