How do I pass a type as parameter in this method?
Marc
jckj33 at gmail.com
Tue Dec 19 15:19:53 UTC 2017
On Tuesday, 19 December 2017 at 00:01:00 UTC, Ali Çehreli wrote:
> On 12/18/2017 03:54 PM, Ali Çehreli wrote:
>> On 12/18/2017 02:58 PM, Marc wrote:
>
> Here's another experiment:
>
> template FirstOf(T...) {
> template otherwise(D) {
> static if (T.length == 0) {
> enum otherwise = D.init;
> } else {
> enum otherwise = T[0];
> }
> }
> }
>
> void main() {
> static assert (FirstOf!(1.5, "hello").otherwise!int == 1.5);
> static assert (FirstOf!("world", [1]).otherwise!int ==
> "world");
> static assert (FirstOf!().otherwise!int == 0);
> }
>
> Ali
Thanks four answer. I'll be using this one. I was messing around
and getting multiple arguments to template function too. I like
the naming too, it made code clear, imo.
It's possible to have overload where one take a type name and the
other a variable (constant value actually)? something like this
(also imaginary code):
> template FirstOf(TP...) {
> template otherwise(D) {
> static if(TP.length > 0) {
> enum otherwise = TP[0];
> } else {
> enum otherwise = D.init;
> }
> }
> template otherwise(D value) {
> static if(TP.length > 0) {
> enum otherwise = TP[0];
> } else {
> enum otherwise = value;
> }
> }
> }
So I can use like this:
> int index = FirstOf!(myTuple).otherwise!int;
> int value = FirstOf(myTuple2).otherwise!(10);
with my limited template knowledge, I know I can write it like
this:
> template otherwise(D, D value) {
> static if(TP.length > 0) {
> enum otherwise = TP[0];
> } else {
> enum otherwise = value;
> }
> }
So the call would go like this:
> int value = FirstOf(myTuple2).otherwise!(int, 10);
But for simplicity I'd like to infer the type from constant value
passed in parameter, in that case, the integer value of 10.
More information about the Digitalmars-d-learn
mailing list