Share via


範本 ref 類別 (C++/CX)

C++ 範本不會發行到中繼資料,因此,在您的程式中不能有公用或受保護存取範圍。 當然,您可以在內部自己的程式中使用 Standard C++ 範本。 此外,您可以將私用 ref 類別定義為樣板,並可以將明確特製化的樣板 ref 類別宣告為公用 ref 類別的私用成員。

撰寫 ref 類別樣板

下列範例示範如何將私用 ref 類別宣告為樣板,也會示範如何宣告 Standard C++ 範本,以及如何將這兩個樣板同時宣告為公用 ref 類別的成員。 請注意,標準 C++ 樣板可以透過Windows 執行階段類型特製化,在此案例中為 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;
    };
}

另請參閱

類型系統 (C++/CX)
C++/CX 語言參考
命名空間參考