Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
};
like image 998
dkackman Avatar asked Dec 26 '09 04:12

dkackman


People also ask

What does C++/CLI stand for?

C++/CLI is variant of the C++ programming language, modified for Common Language Infrastructure. It has been part of Visual Studio 2005 and later, and provides interoperability with other . NET languages such as C#. Microsoft created C++/CLI to supersede Managed Extensions for C++.

What is the difference between C++ and C++/CLI?

C++ runs directly as binary complied for your hardware. C++ cli is a c++ extension that is used to interface with the MS common language runtime. It complies to IL normally and is executed inside the . net runtime.

Is CLR and CLI same?

C++/CLI is a complete different thing from CLR. One is a language and the other is a VES implementation.

Is C++/CLI deprecated?

C++/CLI is not deprecated. The Visual C++ team invested in C++/CLI Intellisense in Visual Studio 2012; a feature that was cut from Visual Studio 2010.


1 Answers

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;
};
like image 69
dkackman Avatar answered Oct 01 '22 10:10

dkackman