Re: Template Parameters in Struct Member Functions

2015-08-22 Thread Mike Parker via Digitalmars-d-learn

On Saturday, 22 August 2015 at 16:49:26 UTC, DarthCthulhu wrote:
I'm having difficulty understanding how templates operate as 
function parameters.


Say I have this:

struct ArrayTest {

void arrayTest(T) (T arrayT) {

writeln(arrayT);
}
}

unittest {

ArrayTest test;

float farray[] = [
0.5f,  0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
-0.5f, -0.5f, 0.0f,
-0.5f,  0.5f, 0.0f
];

test.arrayTest(farray);

}

Everything works peachy as expected. But as soon as I add 
another parameter to the arrayTest function like so (and 
changing the unit test to match):


void arrayTest(T, int passing) (T arrayT) { ... }

I get 'cannot deduce function from argument types' errors.

Specifically stating the type of the function doesn't seem to 
help:


test.arrayTest(float [])(farray, 1);


test.arrayTest!(float, 1)(farray);



Re: Template Parameters in Struct Member Functions

2015-08-22 Thread Mike Parker via Digitalmars-d-learn

On Saturday, 22 August 2015 at 17:08:36 UTC, Mike Parker wrote:

void arrayTest(T, int passing) (T arrayT) { ... }

I get 'cannot deduce function from argument types' errors.

Specifically stating the type of the function doesn't seem to 
help:


test.arrayTest(float [])(farray, 1);


test.arrayTest!(float, 1)(farray);


Sorry, that should be:

test.arrayTest!(float[], 1)(farray);

In your template declaration, you have declared two template 
parameters, T and passing, and one function parameter, arrayT. It 
is equivalent to:


template arrayTest(T, int passing) {
void arrayTest(T arrayT) {...}
}

To call the function, you have to explicitly instantiate the 
template with the instantiation operator (which is !) and give it 
two arguments as template parameters in the first pair of 
parentheses, then you have to give it one function argument in 
the second pair of parentheses. The template parameters are 
compile-time arguments, the function parameter is runtime.


With this form:

void arrayTest(T)(T arrayT) {...}

There is no need for the explicit instantiation. The compiler is 
able to deduce what T should be since it has all the information 
it needs, so you can call it like:


test.arrayTest(foo);