Passing variables, preserving UDAs: A Gripe

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Tue Feb 7 23:57:15 PST 2017


On 07.02.2017 22:59, Nick Sabalausky wrote:
> Suppose I have some code that operates on a variable's value and its
> UDAs. And I want to refactor that code into a reusable function. Sounds
> simple enough, right?
>
> So, consider a basic example:
>
> ----------------------------
> class Foo
> {
>     @("Hello")
>     string s;
> }
>
> void doStuff(alias var)()
> {
>     var = "abc";
>
>     import std.traits;
>     assert(hasUDA!(var, "Hello") == true);
> }
>
> void main()
> {
>     @("Hello")
>     string s;
>     doStuff!(s);
>
>     auto foo = new Foo();
>     // Error: need 'this' for 'doStuff' of type 'pure nothrow @nogc
> @safe void()'
>     doStuff!(foo.s);
> }
> ----------------------------
>
> Note the error. Naturally, that cannot compile, because you can't
> instantiate a template based on the value of a variable at runtime (ie,
> based on the value of `foo`).

It actually can compile. (It just doesn't.)
There is no essential difference between the two cases.


More information about the Digitalmars-d mailing list