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

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 30 05:57:51 PDT 2014


On Friday, 30 May 2014 at 12:35:46 UTC, francesco cattoglio wrote:
> class MyClass {
[...]
> 	const (Foo) getQ () const { return _Q; } // OK
> 	// const Foo getQ () const { return _Q; } // fails
> }
[...]
> I don't really understand what's going on here. Why is "const 
> Foo getQ()" wrong?

The "const" in the front is the same as the front in the back.
They both apply to the method, not to the return type. This is
because you can put all method attributes in both places. And the
compiler doesn't seem to care when you repeat them. Maybe it
should.

E.g. `pure void f() pure {}` = `pure void f() {}` = `void f()
pure {}`

> And why is "const(Foo) getQ" so much different? (e.g: this is 
> an explicit cast, right? Is there anything that might go wrong?)

It's not a cast. It's the unambiguous notation for a qualified
type. Often you can omit the parentheses. With methods you
cannot. With methods you need the parentheses to let the compiler
know that you indeed mean the return type to be const, not the
method itself.


More information about the Digitalmars-d-learn mailing list