Use C++ CLI template class in C#

久未见 提交于 2019-12-21 09:31:21

问题


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?


回答1:


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>
{
};



回答2:


Reflector is lying a little bit here. The name of the class is not actually Number<int>. It is actually 'Number<int>'. Notice the single quotes. These are only visible when you view the type name with ildasm.

I believe this is done to make the type unbindable in most languages as they have no way of understanding how a C++ template actually works. This makes it effectively only visible to the C++ compiler which is appropriate since it's the only MS compiler that actually supports templates (templates != generics).




回答3:


If your goal is to create a parametrized type in C++ CLI, and then use that type from C#, I think that you need to create a generic type rather than a template type (see Stan Lippman's Blog for the reasons why both methods exist). See here for information on how to create generic types in C++ CLI.



来源:https://stackoverflow.com/questions/681590/use-c-cli-template-class-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!