Templated Struct Constructor
Steven Schveighoffer
schveiguy at yahoo.com
Mon Dec 12 05:05:58 PST 2011
On Sat, 10 Dec 2011 02:42:30 -0500, Andrew Wiley
<wiley.andrew.j at gmail.com> wrote:
> On Sat, Dec 10, 2011 at 1:23 AM, Andrew Wiley <wiley.andrew.j at gmail.com>
> wrote:
>> Is there a syntax that allows me to specify arguments to a templated
>> constructor for a struct? The intuitive way looks like this, but it
>> doesn't work.
>>
>> ---
>> struct Test {
>> this(T, bool b)(T info) if((b && something ) || (!b &&
>> somethingElse)) {
>>
>> }
>> }
>>
>> void main() {
>> Test test = Test!(int, true)(5); // Error: template instance
>> Test!(int,true) Test is not a template declaration, it is a struct
>> }
>> ---
>
> Looks like I can work around it by doing this:
> ---
> template makeTest(T, bool b) {
> static if((b && something) || (!b && somethingElse)) {
> alias Test makeTest;
> }
> else static assert(0, "some error message");
> }
> struct Test {
> private:
> this(T)(T info) {
> }
> }
> void main() {
> Test test = Test!(int, true)(5); // Error: template instance
> Test!(int,true) Test is not a template declaration, it is a struct
> }
> ---
>
> But this solution isn't very satisfying because Test is no longer
> directly protected by the static checks I want.
A constructor is just a function. Use an IFTI-able function instead:
Test makeTest(bool b, T)(T info) {...; return Test(realCtorArgsHere);}
As a bonus, you don't have to specify T because of IFTI (which is why I
made it the second template parameter).
C++ and D are full of little trinkets like this. The earliest example I
can remember is std::make_pair from C++.
-Steve
More information about the Digitalmars-d
mailing list