Differences between "const Type function()" and "const(Type) function()"

Dicebot via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 30 06:03:06 PDT 2014


On Friday, 30 May 2014 at 12:35:46 UTC, francesco cattoglio wrote:
> Today I got the following compile error:
> "Cannot implicitly convert expression (<blabla>) of type 
> const(<Type>) to <Type>"
> and this is a reduced example ( also on 
> http://dpaste.dzfl.pl/f2f3bd921989):
>
> module test;
> import std.stdio;
>
> class Foo {
> 	int i = 42;	
> }
>
> class MyClass {
> 	private { Foo _Q; }
> 	this() {_Q = new Foo;}
> 	Foo getQ () { return _Q; }
> 	const (Foo) getQ () const { return _Q; } // OK
> 	// const Foo getQ () const { return _Q; } // fails
> }
>
> void main() {
> 	const MyClass instance = new MyClass;
> 	writeln(instance.getQ.i);
> }
>
> I don't really understand what's going on here. Why is "const 
> Foo getQ()" wrong?
> And why is "const(Foo) getQ" so much different? (e.g: this is 
> an explicit cast, right? Is there anything that might go wrong?)

Outcome of terrible decision to apply front `const` to 
function/method type itself and not return type.


More information about the Digitalmars-d-learn mailing list