Use class template as a type

Bauss via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Nov 30 01:44:38 PST 2016


On Tuesday, 29 November 2016 at 15:56:23 UTC, Jerry wrote:
> On Monday, 28 November 2016 at 11:26:41 UTC, dm wrote:
>> ```
>> abstract class MyClass(T)
>> {
>>   public:
>>    @property const(T) value(){return _value;}
>>    @property void value(T val){_value = val;}
>> ...
>>   private:
>>    T _value;
>> ...
>> }
>
> To avoid having to use the Object class directly you can make 
> an base class of the class template.
> Like:
>
> ```
> abstract class MyClass {}
> abstract class MyClassImpl(T)
> {
> public:
>     @property const(T) value(){return _value;}
>     @property void value(T val){_value = val;}
>  ...
>    private:
>     T _value;
>  ...
> }
>
> MyClassInt and float inherits from MyClassImpl
> ```
>
> And use it like:
>
> ```
> void main() {
>    MyClass[] objs;
>    objs ~= new MyClassFloat();
>    objs ~= new MyClassInt();
> }
> ```

I would rather go with an interface than a base class.




More information about the Digitalmars-d-learn mailing list