Thread overview
Passing functions as template parameter and assigning default values to them
Jun 21, 2015
kerdemdemir
Jun 21, 2015
biozic
Jun 21, 2015
kerdemdemir
June 21, 2015
Hi,

I need to find the index of maximum element so my code:

int indexOfMax(R)(R range)
{	
    alias Type = typeof(range.front().re);  ----> I don't like .re here
    Type max = 0;
    size_t maxIndex = 0;
    foreach ( index,elem; range )
    {
    	if ( elem.re > max )    -----> And also here
    	{
    	    max = elem.re;
    	    maxIndex = index;
    	}
    }
    return maxIndex;
}

Since my range contains Complex!double types I have to add ".re" for current implementation. But I want to be more generic. Like how std.algorithm.map is.
Like: range.map!(a => a.re).

So what I want to achive is :

indexOfMax!(a => a.re)(complexRange); ----> implement algorithm on a.re
indexOfMax(intRange); -----> if a function is not given act like (a => a)

Any advice with template function parameters or mixins will make me happy.

Regards
Erdem


June 21, 2015
On Sunday, 21 June 2015 at 09:34:51 UTC, kerdemdemir wrote:
> Hi,
>
> I need to find the index of maximum element so my code:
>
> int indexOfMax(R)(R range)
> {	
>     alias Type = typeof(range.front().re);  ----> I don't like .re here
>     Type max = 0;
>     size_t maxIndex = 0;
>     foreach ( index,elem; range )
>     {
>     	if ( elem.re > max )    -----> And also here
>     	{
>     	    max = elem.re;
>     	    maxIndex = index;
>     	}
>     }
>     return maxIndex;
> }
>
> Since my range contains Complex!double types I have to add ".re" for current implementation. But I want to be more generic. Like how std.algorithm.map is.
> Like: range.map!(a => a.re).
>
> So what I want to achive is :
>
> indexOfMax!(a => a.re)(complexRange); ----> implement algorithm on a.re
> indexOfMax(intRange); -----> if a function is not given act like (a => a)
>
> Any advice with template function parameters or mixins will make me happy.
>
> Regards
> Erdem

You can use a template alias parameter with a default value that is your default lambda:

int indexOfMax(alias fun = a => a, R)(R range)
{
    // Use `fun` here like a function.
}

-- Nico

June 21, 2015
On Sunday, 21 June 2015 at 10:06:15 UTC, biozic wrote:
> You can use a template alias parameter with a default value that is your default lambda:
>
> int indexOfMax(alias fun = a => a, R)(R range)
> {
>     // Use `fun` here like a function.
> }
>
> -- Nico

Thanks a lot, it works !!