const and immutable values, D vs C++?

Steven Schveighoffer schveiguy at gmail.com
Wed Dec 4 23:27:49 UTC 2019


On 12/4/19 5:57 PM, Ola Fosheim Grøstad wrote:
> On Wednesday, 4 December 2019 at 22:51:01 UTC, Ola Fosheim Grøstad wrote:
>> Is there a way to specify in generic code that you want the best fit 
>> of a const/immutable reference depending on the return type (but not a 
>> mutable one)?
> 
> I mean, if f() return mutable or const then it should be const, but if 
> it returns immutable then it should be immutable. Something like:
> 
> readonly myref = f()
> 
> 
void foo(alias f)()
{
    alias ConstType = const(typeof(f()));
    pragma(msg, ConstType);
}

     const(int) a() { return 1; }
immutable(int) b() { return 1; }
           int  c() { return 1; }

void main()
{
     foo!a(); // const(int)
     foo!b(); // immutable(int)
     foo!c(); // const(int)
}

-Steve


More information about the Digitalmars-d-learn mailing list