Deducing a template retrun parameter type based on an assignment?
Vlad Levenfeld via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jan 29 22:58:57 PST 2015
On Friday, 30 January 2015 at 06:35:31 UTC, Jeremy DeHaan wrote:
> I have a template fuction that looks like this:
>
> immutable(T)[] getString(T)() const
> if (is(T == dchar)||is(T == wchar)||is(T == char))
>
> Basically, I was hoping that the type would be deduced based on
> the prameter that was being assigned to like so.
>
> string ret = thing.getString();
>
> Apparently that does not work, though. I get informed that the
> type of the template is not able to be deduced. I'm curious as
> to why it was not able to deduce it on its own.
>
> Additionally, and I haven't run my code to try this yet, but
> giving T a default type compiled to my surprise.
>
> immutable(T)[] getString(T=char)() const
> if (is(T == dchar)||is(T == wchar)||is(T == char))
>
> Is something like this supposed even to work?
for template type deduction to work, you have to supply an
argument. Your type signature would need to look like this:
immutable(T)[] getString(T)(T arg) const
and then T would be deduced from arg.
But string ret = thing.getString(); won't compile because it is
rewritten to getString(thing), but your getString function takes
no runtime parameters. It looks like the signature I wrote
earlier is what you actually want.
As to your second example, it'll work fine. Basically your
signature says "only accept dchar, wchar or char, but if
nothing's been specified, default to char". But if you rewrite
getString to take one parameter, then the default template arg is
redundant.
More information about the Digitalmars-d-learn
mailing list