www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Struct template type inference

Inside std.range there is a template struct that implements the chain:

struct ChainImpl(R...) {

plus a tiny helper function 'chain' that's usually the one used in the user
code:

Chain!(R) chain(R...)(R input) {
    static if (input.length > 1)
        return Chain!(R)(input);
    else
        return input[0];
}


Similar pairs of struct template + little helper function are quite common in
both std.range, in my libraries, and probably in lot of generic D code that
uses struct templates. The purpose of the little function is to instantiate the
struct template with the correct type. This is a simplified example:

struct Foo(T) {
    T x;
}
auto foo(T)(T x) {
    return Foo!T(x);
}
void main() {
    auto f = foo(10);
}


In this code if the helper foo() function doesn't exist, and if the data type T
is a bit complicated, the programmer might need to write something like (here T
is not complicated):

struct Foo(T) {
    T x;
}
void main() {
    auto somevalue = 10;
    auto f = Foo!(typeof(somevalue))(somevalue);
}


that is not handy.

So to keep code the simple and to avoid the definition of those helper
functions, struct templates can be enhanced, so they can infer their template
type in some way.

But the situation is not always so simple as in that Foo struct template. The
struct template can define constructors and initializers. Even if that case of
that chain() helper function it contains a bit of compile-time logic to
simplify the case with just one iterable.

So I don't know if there is some clean way to infer the types for the struct
template.

Bye,
bearophile
Apr 13 2010