With a class you can do this:
class Data
{
        string s;
        this(string s)
        {
                this.s = s;
        }
}

void f(Data x ...)
{
        import std.stdio;
        writeln(x.s);
}

void main()
{
    f("hello"); //convert argument implicitly to type `data`.
}

See Typesafe Variadic Functions at http://dlang.org/function.html

I don't know why you can't do it with a struct.

As a workaround, you can do this:

class Construct(T)
{
        T t;
        this(Q)(Q q)
        {
                static if(is(Q : T))
                {
                        t = q;
                }
                else
                {
                        this.t = T(q);
                }
        }
}

struct Data
{
        string s;
}

void f(Construct!Data xC ...) //construct the wrapper class
{
        auto x = xC.t; //get the contents.
        
        import std.stdio;
        writeln(x.s);
}

void main()
{
        f("hello");
        f(Data("world"));
}


Overall it's probably best to define f as:

void f(Data x)
{
        import std.stdio;
        writeln(x.s);
}

void f(Construct!Data xC ...)
{
        .f(xC.t);
}

To avoid any overhead when calling normally as well as separating the definition of the real function from the concern of automatic construction/conversion.

Nice technique, I'll remember that. Presumably this can't be extended to functions with more than one Data parameter.

What a curious corner of the language! I am somewhat mystified as to the reasoning/intuition behind the presence of this feature for classes (and not structs). Anybody?

Reply via email to