Quarkstrudel im Kopf

July 25, 2014 / Martin

Duck Typing in C++

Imagine you would like to have something similar to Duck Typing from Python in C++. Duck Typing assumes that the type of a class makes sense in a context if the code finds all the methods that it needs. As long as it quacks like a duck it must be a duck. For example you might have a code snippets with a template parameter and you would like to do one thing if the type implements a certain method and do something else if this method does not exist.

A neat feature of C++11 is that it allows you to achieve exactly that without much code overhead. The full thing is also discussed on Stack Overflow.

#include <iostream>

class A {
  public:
    void method() const;
};

void A::method() const {
  std::cout << "class A" << std::endl;
}

class B {

};

template <typename T>
auto fun(const T& t, int)
-> decltype(t.method(), void()) {
  t.method();
}

template <typename T>
void fun(const T& t, short) {
  std::cout << "default" << std::endl;
}

int main(int argc, const char* argv[]) {
  fun(A(), 0);
  fun(B(), 0);

  return 0;
}

This little program should output:

class A
default

The nice thing is that this does not involve any kind of inheritance. So this is even applicable for classes that you as a user cannot change anymore. Compared to Python’s Duck Typing the compiler decides which function should be called. So this does not have any impact on the runtime.

The trick that makes this work is the concept of Substitution failure is not an error (SFINAE). So in the example above the substitution of type B will fail in the decltype as B is not providing the right method.