#include 

struct Duck {
    void quack(std::ostream& out) {
        out << "Quack!" << std::endl;
    }
};

struct Platypus {
    void quack(std::ostream& out) {
        int* i = NULL;
        out << *i << std::endl;
    }
};

template 
void do_quack(std::ostream& out,
        MaybeDuck duck) {

    duck.quack(out);
}

int main() {
    Duck duck;
    Platypus platypus;

    do_quack(std::cout, duck);
    do_quack(std::cout, platypus);
}

C++ has compile-time duck typing

(See it live on Coliru)

The C++ compiler doesn’t actually do much semantic checks in terms of whether it can “figure out” whether the type you give a template is correct.

All it does is kind of “copy-and-paste” the type you give it into the placeholder type, and sees if it compiles correctly.

Here, our two classes will both quack(), but will not necessarily do the same
thing. One will print; the other will most likely give a segmentation fault, because you’re trying to dereference a  NULL pointer.

In other words, C++ does not do special semantic checking on templates unless you do it yourself.

Hence, this program crashes.

So what’s the solution?

There are many.

Advertisements