Template error messages

bearophile bearophileHUGS at lycos.com
Sun Jul 5 07:51:34 PDT 2009


If I compile the following D1 code:

// D1 code
C pick(C)(ref C x, ref C y)
    // for D2:
    /* if (__traits(compiles, better(C.init, C.init))) */ {
        if (better(x, y))
            return x;
        else
            return y;
}

struct Apple {
    int rating;
}

struct Orange {
    int rating;
}

bool better(ref Apple a, ref Apple b) { return b.rating < a.rating; }

void main() {
    auto a1 = Apple(3), a2 = Apple(5);
    auto a3 = pick(a1, a2);

    auto o1 = Orange(3), o2 = Orange(5);
    auto o3 = pick(o1, o2);
}

The errors shown by LDC/DMD (the error on line 26 is the most important, but it's buried under several other lines of error messages), are:

Line 5: function t.better (Apple ,Apple ) does not match parameter types (Orange ,Orange )
Line 5: Error: cannot implicitly convert expression (x) of type Orange to Apple
Line 5: Error: cast(Apple )x is not an lvalue
Line 5: Error: cannot implicitly convert expression (y) of type Orange to Apple
Line 5: Error: cast(Apple )y is not an lvalue
Line 26: template instance t.pick!(Orange ) error instantiating


While the following equivalent C++ code:

template <class C> const C& pick(const C& x, const C& y) {
    if (better(x, y))
        return x;
    else
        return y;
}

struct Apple {
    Apple(int r) : rating(r) {}
    int rating;
};

struct Orange {
    Orange(int r) : rating(r) {}
    int rating;
};

bool better(const Apple& a, const Apple& b) { return b.rating < a.rating; }

int main() {
    Apple a1(3), a2(5);
    Apple a3 = pick(a1, a2);

    Orange o1(3), o2(5);
    Orange o3 = pick(o1, o2);
}


Compiled with G++ 4.3.3 gives the following error message, that shows the line 24 before the other ones:

apple_test_cpp.cpp: In function 'const Comparable& pick(const Comparable&, const Comparable&) [with Comparable = Orange]
':
apple_test_cpp.cpp:24:   instantiated from here
apple_test_cpp.cpp:4: error: invalid initialization of reference of type 'const Apple&' from expression of type 'const O
range'
apple_test_cpp.cpp:17: error: in passing argument 1 of 'bool better(const Apple&, const Apple&)'

I'd like DMD to act as G++ and to show first of all the error relative to where the template was (tried to be) instantiated.

Bye,
bearophile



More information about the Digitalmars-d mailing list