www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 19448] New: Add a trait to test template arguments without


          Issue ID: 19448
           Summary: Add a trait to test template arguments without
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: elpenguino+D gmail.com

Designing interfaces with the assumption that a template will compile if the
arguments match leads to silent failure. std.conv.text is one such offender. If
a templated toString exists for the type but causes compiler errors on
instantiation, text() will incorrectly fall back on some other method.


void main() {
        writeln(X().text); //X(false)? That's not what I wanted!

struct X {
        bool a;
        void toString(T)(T sink) {
        void easilyMisspelledMethod(T)(T sink) {
                put(sink, "Hello!");

I'd like to propose a simple trait to resolve this.


void x(T : int)() {

static assert(!__traits(compiles, x!bool()));
static assert(__traits(templateMatches, x, int));
static assert(__traits(templateMatches, x, short));
static assert(!__traits(templateMatches, x, string));

void doSomething(alias T)() {
        static if(__traits(templateMatches, T, int)) {

static assert(!__traits(compiles, doSomething!x())); //x!int exists, but
doesn't compile, so this is expected


Nov 29 2018