minElement on array of const objects

Temtaime temtaime at gmail.com
Mon Nov 13 10:31:52 UTC 2017


On Monday, 13 November 2017 at 10:20:51 UTC, Aurelien Fredouelle 
wrote:
> Hi all,
>
> It seems that it is not possible to use minElement on an array 
> of const objects:
>
> class A
> {
>   int val;
> }
>
> const(A) doStuff(const(A)[] v)
> {
>   import std.algorithm.searching : minElement;
>   return v.minElement!"a.val";
> }
>
> This gets the following compiler error:
>
> std/algorithm/searching.d(1256,28): Error: cannot implicitly 
> convert expression (front(r)) of type const(A) to app.A
> std/algorithm/searching.d(1286,35): Error: cannot implicitly 
> convert expression (r[i]) of type const(A) to app.A
> std/algorithm/searching.d(1258,36): Error: template instance 
> std.algorithm.searching.extremum!("a.val", "a < b", const(A)[], 
> A) error instantiating
> std/algorithm/searching.d(3345,24):        instantiated from 
> here: extremum!("a.val", "a < b", const(A)[])
> source/app.d(11,11):        instantiated from here: 
> minElement!("a.val", const(A)[])
>
> Is there a reason why this is not allowed? Shouldn't minElement 
> be able to return a const(A) in this situation?
>
> Thanks,
> Aurelien

It should not until it uses recursion to find min element.

const(Class) res = ...;
...
return res;

Algorithm tries to assign to res variable and fails because in D 
const(Class) means both const object and const reference to it. 
So we cannot assign another reference to const(Class) variable.


More information about the Digitalmars-d-learn mailing list