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

francesco cattoglio via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 30 05:35:45 PDT 2014


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?)


More information about the Digitalmars-d-learn mailing list