C++: Template duck-typing in 30 lines

#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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s