template auto instantiation when parameters empty
Erik Smith via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu May 5 09:50:27 PDT 2016
On Thursday, 5 May 2016 at 16:12:40 UTC, Steven Schveighoffer
wrote:
> On 5/5/16 12:10 AM, Erik Smith wrote:
>> I want to have a struct template auto instantiate when the
>> template
>> parameters are defaulted or missing. Example:
>>
>> struct Resource(T=int) {
>> static auto create() {return Resource(null);}
>> this(string s) {}
>> }
>>
>> auto resource = Resource.create;
>>
>> As a plain struct it works, but not as a template:
>>
>> struct Resource { // works
>> struct Resource() { // fails
>> struct Resource(T=int) { // fails
>>
>> At the call site, this works, but I'm hoping for a few less
>> symbols:
>>
>> auto resource = Resource!().create;
>>
>> Any ideas?
>
> Instead of static method, use an external factory method:
>
> static auto createResource(T = int)()
> {
> return Resource!T(null);
> }
>
> And I wouldn't bother with making Resource's T have a default,
> as you'd still have to instantiate it with Resource!() to get
> the default.
>
> -Steve
Alias works at the cost of adding a 2nd type name:
alias Res = Resource!();
auto res = Res.create
The other problem is that the alias definition by itself
instantiates, which I can't afford.
I have createResource() now, it just doesn't fit well with the
rest of the calling styles.
There is also this approach, which might be slightly more
idiomatic
struct Resource(T) {}
struct Policy {}
auto create(alias T)() {
T!Policy r;
return r;
}
auto r = create!Resource;
More information about the Digitalmars-d-learn
mailing list