www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - templates and functions

reply Daniel <daniel.lincke pik-potsdam.de> writes:
Hi,

I'm trying to reimplement something like this C++ code in D:

template<Class T>
Class A {
   ...
}

template<Class T>
A<T> some_function() {
   ...
}

While I can implement the class:

class A(X) {
   ...
}

I fail with the function, due to the fact that I don't know/find the correct
syntax for this. The version

A(X) some_function() {

}

fails with the message
function declaration without return type. (Note that constructors are always
named 'this')
which is understandable. Any idea how the correct syntax is?

Thanx, daniel
Sep 08 2011
parent reply "Simen Kjaeraas" <simen.kjaras gmail.com> writes:
On Thu, 08 Sep 2011 18:53:55 +0200, Daniel <daniel.lincke pik-potsdam.de>  
wrote:

 Hi,

 I'm trying to reimplement something like this C++ code in D:

 template<Class T>
 Class A {
    ...
 }

 template<Class T>
 A<T> some_function() {
    ...
 }

 While I can implement the class:

 class A(X) {
    ...
 }

 I fail with the function, due to the fact that I don't know/find the  
 correct
 syntax for this. The version

 A(X) some_function() {

 }

 fails with the message
 function declaration without return type. (Note that constructors are  
 always
 named 'this')
 which is understandable. Any idea how the correct syntax is?
A!X some_function(X)() { //... } -- Simen
Sep 08 2011
parent reply Daniel <daniel.lincke pik-potsdam.de> writes:
Thx, Simen.

Unfortunately, this works only for concretet types, but not for type parameters.
Example:

class Test(A) {

    A do_nothing(A x) {
	return x;
    }
}

/* WORKS */
Id_Func!int test() {
    return new Test!(int);
}

/* Error : undefined identifier A */
Id_Func!A test() {
    return new Test!(A);
}
Sep 26 2011
parent reply Daniel <daniel.lincke pik-potsdam.de> writes:
Sorry, minor mistakes ;)
Again:

Thx, Simen.

Unfortunately, this works only for concretet types, but not for type parameters.
Example:

class Test(A) {

    A do_nothing(A x) {
       return x;
    }
}

/* WORKS */
Test!int test() {
    return new Test!(int);
}

/* Error : undefined identifier A */
Test!A test() {
    return new Test!(A);
}
Sep 26 2011
parent David Nadlinger <see klickverbot.at> writes:
On 9/26/11 6:00 PM, Daniel wrote:
 /* Error : undefined identifier A */
 Test!A test() {
      return new Test!(A);
 }
You are probably looking for Test!A test(A)() …, which is equivalent to template test(A) { Test!A test() { … } } . Also, you might want to ask questions like this on the digitalmars.D.learn sub-newsgroup. David
Sep 26 2011