Advertisement
andybuckley

Duck typing (rather than inheritance) in C++

Feb 19th, 2015
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.51 KB | None | 0 0
  1. // -*- C++ -*-
  2.  
  3. #include <string>
  4. #include <iostream>
  5. using namespace std;
  6.  
  7.  
  8. struct A {
  9.   int foo() const { return 3; }
  10.   double bar() const { return 3.0; }
  11. };
  12.  
  13. struct B {
  14.   int foo() const { return 10000; }
  15.   string bar() const { return "B is for BAR"; }
  16. };
  17.  
  18. template <typename T>
  19. void fn(const T& obj) {
  20.   cout << obj.foo() << " " << obj.bar() << endl;
  21. }
  22.  
  23.  
  24. int main() {
  25.   A a;
  26.   fn(a);
  27.   B b;
  28.   fn(b);
  29.   return 0;
  30. }
  31.  
  32. // Prints:
  33. //
  34. // 3 3
  35. // 10000 B is for BAR
  36. //
  37. // (as you'd hope)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement