Bug 1816 – Parameter names not visible in return type in function declarations
Status
RESOLVED
Resolution
WONTFIX
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2008-02-05T01:04:25Z
Last change time
2017-09-19T11:48:36Z
Assigned to
No Owner
Creator
Andrei Alexandrescu
Comments
Comment #0 by andrei — 2008-02-05T01:04:25Z
The following code should compile:
typeof(a) identity(T)(T a) { return a; }
void main()
{
auto x = identity(1);
}
In this case it's trivial to replace typeof(a) with T, but in the general case (e.g. mixins, complex expressions) it is necessary to access parameter names in complex expressions inside typeof().
Comment #1 by default_357-line — 2008-02-05T06:25:21Z
[email protected] wrote:
> http://d.puremagic.com/issues/show_bug.cgi?id=1816
>
> Summary: Parameter names not visible in return type in function
> declarations
> Product: D
> Version: unspecified
> Platform: PC
> OS/Version: Linux
> Status: NEW
> Severity: normal
> Priority: P2
> Component: DMD
> AssignedTo: [email protected]
> ReportedBy: [email protected]
>
>
> The following code should compile:
>
> typeof(a) identity(T)(T a) { return a; }
>
> void main()
> {
> auto x = identity(1);
> }
>
> In this case it's trivial to replace typeof(a) with T, but in the general case
> (e.g. mixins, complex expressions) it is necessary to access parameter names in
> complex expressions inside typeof().
>
>
Here's a hack to work around that:
either replace your parameter names with Init!(type) where Init == template Init(T) { T Init; }
or use the return value of a delegate literal created on the spot.
Example: typeof({ T a; return operationOnA(a); }) somefunc(T)(T a) { ... }
I use that technique in scrapple.tools to say "if this string was our function body, what would its return type be?" It's fun! :D
--downs
Comment #2 by andrei — 2008-02-05T10:09:27Z
Thanks, downs, worked great. You forgot a pair of parens, so for others' reference here's the current implementation of binaryPred in std.functional:
template binaryPred(string comp) {
// @@@BUG@@@: typeof(mixin(comp)) should work
typeof({ ElementType a, b; return mixin(comp);}())
binaryPred(ElementType)(ElementType a, ElementType b)
{
return mixin(comp);
}
}
unittest
{
alias binaryPred!(q{a < b}) less;
assert(less(1, 2) && !less(2, 1));
assert(less("1", "2") && !less("2", "1"));
}
Comment #3 by simen.kjaras — 2017-09-19T11:48:36Z
While the issue described here still exists, the modern-day equivalent of the give code would use auto, and any complex typeof() expressions would almost certainly need to be repeated inside the function body in any case, where the parameter is available.
Closing this. If there are compelling use cases, reopen it with example code.