Return by 'ref' problems...

H. S. Teoh hsteoh at quickfur.ath.cx
Fri May 4 07:19:08 PDT 2012


On Fri, May 04, 2012 at 04:57:30PM +0300, Manu wrote:
> On 4 May 2012 16:53, H. S. Teoh <hsteoh at quickfur.ath.cx> wrote:
[...]
> > Yeah, I've recently started building the habit of always using
> > parentheses with const applied to a type, in order to make it less
> > confusing with const as applied to a function. Even though it's
> > legal to write:
> >
> >        int func(const T t) {...}
> >
> > nowadays I prefer to write:
> >
> >        int func(const(T) t) {...}
> >
> > so that when you need to return const, the syntax is more
> > consistent:
> >
> >        const(T) func(const(T) t) {...}
> >
> > and it doesn't visually clash so much with const as applied to the
> > function itself:
> >
> >        const(T) func(const(T) t) const {...}
> >
> > This is one of the warts in D syntax that I find annoying.
> >
> 
> Yeah I really hate this too. I'd like to see const(T) strictly
> enforced, considering the potential for ambiguity in other situations.
> 
> But I'm still stuck! :(
> How can I do what I need to do?

Argh... this is really annoying. So I tried all sorts of combinations of
function pointer syntax in order to get the correct type for a ref
function that returns const(T), but couldn't. So I decided to let the
language tell me itself what the type is:

	import std.stdio;
	struct S {}
	ref const(S) func() { ... }
	void main() {
		auto fp = &func;
		writeln(typeid(fp));
	}

This program outputs:

	const(test.S)()*

So I copy-n-paste this type into the source:

	const(test.S)()* fp = &func;

and I get:

	test.d(15): function declaration without return type. (Note that constructors are always named 'this')
	test.d(15): no identifier for declarator const(test.S)()
	test.d(15): semicolon expected following function declaration

This is a language inconsistency, and very stupid.

But anyway, Walter was all fawning over voldemort types recently, so I
thought, well, apparently we have here another case of a voldemort type:
no matter what you try to call it, the compiler either doesn't
understand it or rejects it. So let's turn the language upon its own
head:

	typeof(&func) fp = &func;

And lo and behold, it works!! So it's very stupid, but if you at least
have an exemplary function that you'd like to make a function pointer
out of, you can use this workaround to name its type.

Yeah, I recommend filing a bug for this. The type of &func needs to be
nameable without resorting to using typeof(&func), but at least you can
use the latter as a temporary workaround until dmd is fixed. :-)


T

-- 
If you look at a thing nine hundred and ninety-nine times, you are
perfectly safe; if you look at it the thousandth time, you are in
frightful danger of seeing it for the first time. -- G. K. Chesterton


More information about the Digitalmars-d mailing list