digitalmars.D - Named parameters workaround
- Matthias Walter (44/44) Feb 09 2012 -----BEGIN PGP SIGNED MESSAGE-----
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, named parameters have been discussed awhile ago and it seems to me that they won't get into the language soon. I came up with a workaround that makes it possible to use them with some extra typing. Suppose we have a function foo(int a, int b, string c, MyStruct d, MyClass e); and want to call with with named parameters. It is possible to write a wrapper function as follows foo(N)(N n) { foo( n.has!"a"() ? n.get!"a"() : 42, // 42 is the default parameter n.get!"b"(), // Complain if b is not given n.has!"c"() ? n.get!"c"() : "foo", n.has!"d"() ? n.get!"d"() : MyStruct(), n.has!"e"() ? n.get!"e"() : new MyClass() ); } and then call it foo(named!"c,b,e"("Foo", 0, new MyClass())); With some more work we could also allow foo(named!"c"("Foo"), named!"b"(0), named!"e"(new MyClass())); All this can be handled by a templated Wrapper-Object that is created by named()(). When doing the code generation of the wrapper object via a mixin, we could also allow ref parameters (with named!"ref e"(my_class) and by storing a pointer). Of course, the code for the wrapper can be inlined because the presence of every parameter can be decided at compile time. Any ideas? Best regards, Matthias -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.11 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAgAGBQJPM5SOAAoJEPdcuJbq5/sRr/MIAL0tJBGWdkhrPUbaS5gqb9ho jkyKW8u+akVMnlTW4BKQ7lHSkJBySZxn4Ty/zIJEmqoIHrlsI308z26miSy5bDeK XcNAx1M+3wUuvYPoJpg3nlARofez9R0n1opfS6DnDYHGYLZH9AK924bwKyChFfP9 a/6mEyPHsMem/+2CWIWJjsLzEBkc+OacgCmzj7dGZfoJBhmF/EjxZgdwYpnA8q3N KYIl28gqyf+JBkmdzVhhDuBMUb1PlqqqnbXS66EaYcQIA7bUESPc8dKJKIQTKVy3 Lq5MSg8BuvMdnIXYVn0HK4R2LWTshZn5kXkfy7EX8Xw4yyT4e6VIkcwDOyy8iMQ= =T4UD -----END PGP SIGNATURE-----
Feb 09 2012