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?
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.
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.
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.
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).
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>
{
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With