Edit

Share via


Template ref classes (C++/CX)

C++ templates are not published to metadata and therefore cannot have public or protected accessibility in your program. You can, of course, use standard C++ templates internally in your program. In addition, you can define a private ref class as a template and you can declare an explicitly specialized template ref class as a private member in a public ref class.

Authoring ref class templates

The following example shows how to declare a private ref class as a template, and also how to declare a standard C++ template and how declare them both as members in a public ref class. Note that the standard C++ template can be specialized by a Windows Runtime type, in this case a Platform::String^.

namespace TemplateDemo
{
    // A private ref class template
    template <typename T>
    ref class MyRefTemplate
    {
    internal:
        MyRefTemplate(T d) : data(d){}
    public:
        T Get(){ return data; }
    private:
        T data;
    };

    // Specialization of ref class template
    template<>
    ref class MyRefTemplate<Platform::String^>
    {
    internal:
        //...
    };

    // A private derived ref class that inherits
    // from a ref class template specialization
    ref class MyDerivedSpecialized sealed : public MyRefTemplate<int>
    {
    internal:
        MyDerivedSpecialized() : MyRefTemplate<int>(5){}
    };

    // A private derived template ref class 
    // that inherits from a ref class template
    template <typename T>
    ref class MyDerived : public MyRefTemplate<T>
    {
    internal:
        MyDerived(){}
    };

    // A standard C++ template
    template <typename T>
    class MyStandardTemplate
    {
    public:
        MyStandardTemplate(){}
        T Get() { return data; }
    private:
        T data;

    };

    // A public ref class with private 
    // members that are specializations of
    // ref class templates and standard C++ templates.
    public ref class MySpecializeBoth sealed
    {
    public:
        MySpecializeBoth(){}
    private:
        MyDerivedSpecialized^ g;
        MyStandardTemplate<Platform::String^>* n;
    };
}

See also

Type System (C++/CX)
C++/CX Language Reference
Namespaces Reference