www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Exercise: Translation C++ -> D

reply mki <none none.com> writes:
Hello,

I am struggling with the D template syntax.
After some thought, my problem can be formulated to translate the following
small C++ program to D:


#include <iostream>

template<class T> class A {};

template<class T> class B {
    public:
        static void tellMe() {
            std::cout << "generic." << std::endl;
        }
};

template<class T> class B<A<T> > {
    public:
        static void tellMe() {
            std::cout << "specialized, size of T is " << sizeof(T) << std::endl;
        }
};

int main() {
    typedef int T1;
    typedef A<int> T2;
    B<T1>::tellMe();
    B<T2>::tellMe();
}

This C++ program compiles without error, the output of the compiled programm is
as expected:
generic.
specialized, size of T is 4


Now my attempt to write the same in D:

//begin D code
import std.stdio;

class A(T) { }

class B(T) {
    static void tellMe() {
        writefln("generic.");
    }
}

class B(TT : A!(T)) {
    static void tellMe() {
        writefln("specialized, sizeof T is ",T.sizeof);
    }
}

void main() {
    alias int T1;
    alias A!(int) T2;
    B!(T1).tellMe();
    B!(T2).tellMe();
}
//end D code

This does not compile, the error is
test3.d(13): Error: undefined identifier T

In C++, the definition of the identifiers which appear in the template
specialization expression are defined after the preceding template keyword
(template< ... HERE ...> ...). But I don't see how this is done in D.

Please someone show me the (probably very simple) solution I am overlooking.

Thanks,

~mki
May 18 2008
parent mki <none none.com> writes:
Just after posting this, I saw the answer of Bill Baxter in digitalmars.d on my
posting there.
Now I know the solution, it is to write

[...]
class B(TT : A!(T), T)
[...]

~mki
May 18 2008