Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use C++ CLI template class in C#

Tags:

c#

.net

c++-cli

I have the following class in C++/CLI and an explicit template instantiation for the int primitive..

template<typename T>
public ref class Number
{
    T _value;
public:
    static property T MinValue
    {
        T get()
        {
            return T::MinValue;
        }
    }

    static property T MaxValue
    {
        T get()
        {
            return T::MaxValue;
        }
    }

    property T Value
    {
        T get()
        {
            return _value;
        }

        void set(T value)
        {
            if( value<MinValue || value > MaxValue)
                throw gcnew System::ArgumentException("Value out of range");

            _value = value;
        }
    }

};

template ref class Number<int>;

On compiling this and inspecting the generated assembly using reflector I am able to see a class called Number<int> but while trying to instantiate this same class in C# the compiler complains about some System::Number class not taking a template argument. What am I doing wrong? Can this be done at all?

like image 788
Autodidact Avatar asked Mar 25 '09 13:03

Autodidact


People also ask

Are templates supported in C?

The main type of templates that can be implemented in C are static templates. Static templates are created at compile time and do not perform runtime checks on sizes, because they shift that responsibility to the compiler.

What is a class template in C?

A class template provides a specification for generating classes based on parameters. Class templates are generally used to implement containers. A class template is instantiated by passing a given set of types to it as template arguments.

Is generic and template the same?

Comparing Templates and GenericsGenerics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime. The common language runtime specifically supports generics in MSIL.

Are there generics in C?

There's already a C-like language which lets you write type-safe generic programs: it's called C++! And if for some reason you really want or need to restrict yourself to using C language features (almost) exclusively, you can disable RTTI, exceptions, and use a technique to avoid linking to libstdc++ (or equivalent).


1 Answers

I have a work around, declare an additional class inheriting the Number<int> class. This class is now visible in C# and can be instantiated.

public ref class MyInt32 : public Number<int>
{
};
like image 90
Autodidact Avatar answered Oct 27 '22 06:10

Autodidact