C++/CLI 同時擁有 ISO C++ Template 與 CLI Generics。Template 允許繼承泛型參數,完美實現類別適配器泛型化:
template<typename T>
ref class DrawAdapter : public IDrawStrategy, public T {
public:
virtual void draw() { paint(); }
};
#include "stdafx.h"
using namespace System;
interface class IDrawStrategy { void draw(); };
interface class IPaint { void paint(); };
ref class Triangle : public IPaint { public: virtual void paint() { Console::WriteLine("Draw Triangle"); } };
ref class Circle : public IPaint { public: virtual void paint() { Console::WriteLine("Draw Circle"); } };
ref class Square : public IPaint { public: virtual void paint() { Console::WriteLine("Draw Square"); } };
template<typename T>
ref class DrawAdapter : public IDrawStrategy, public T {
public:
virtual void draw() { paint(); }
};
ref class Grapher {
IDrawStrategy^ _drawStrategy;
public:
Grapher() : _drawStrategy(nullptr) {}
Grapher(IDrawStrategy^ ds) : _drawStrategy(ds) {}
void drawShape() { if (_drawStrategy != nullptr) _drawStrategy->draw(); }
void setShape(IDrawStrategy^ ds) { _drawStrategy = ds; }
};
int main() {
Grapher^ grapher = gcnew Grapher(gcnew DrawAdapter<Triangle>());
grapher->drawShape();
grapher->setShape(gcnew DrawAdapter<Circle>());
grapher->drawShape();
grapher->setShape(gcnew DrawAdapter<Square>());
grapher->drawShape();
}
// Error: Cannot derive from 'T' because it is a type parameter
class DrawAdapter<T> : IDrawStrategy, T { ... }
C# 2.0/3.0 均不支援繼承泛型參數。C++/CLI 因支援 Template,成為 .NET 語言中唯一能完美實現「繼承泛型參數」類別適配器改良的語言。