October 24, 2016
Hot Topics:

C++ Idioms in BREW: Better Interfaces

  • May 2, 2005
  • By Radu Braniste
  • Send Email »
  • More Articles »

This is similar with this pseudo-construct:

interface Interface
      int bar(const char*);
      int foo(int);

and can be used like:

struct some_baz
   some_baz() : y_(7){}
   int foo(int x) { return x + 1; }
   int bar(char const* s) { return y_; }
   const int y_ ;
struct another_baz 
   another_baz() : y_(9){}
   int foo(int x) { return x - 1; }
   int bar(char const* s) { return y_; }
   const int y_ ;
void demoInterface()
   some_baz f;
   another_baz f2;
   Interface p = f;
      //use p;
   p = f2;
//use p

Of course, the implementation is far from being elegant, but is extremely efficient. Depending on platform and compiler, the gain might be between 15% and 30%. Based on the observation that an Interface can be composed through inheritance (for example, Interface can be seen as inheriting from an interface wrapping bar and another one wrapping foo) and using macros, you can improve the implementation:

typedef  int (*FP1)(void*,  int );
typedef  int (*FP2)(void*,  const char* );

Once the function types are defined (note the void* that appears as the first parameter and is not part of the signature but required by the implementation), the functions can be appended. The signature of the macros contains the name of the interface, position of the function (not required for APPEND_FIRST_INTERFACE_METHOD), its name, and return type. This is the list of all the macros defined:

INHERIT_FROM2    //double interface inheritance
INHERIT_FROM2    //simple interface inheritance

The attached code contains examples as well as the full implementation. As a note of caution, the macro library is very sketchy at this stage and definitely can be improved.

Far from being a natural construct in C++, static interfaces might prove valuable tools when execution speed really matters.


  1. Technical Report on C++ Performance: www.research.att.com/~bs/performanceTR.pdf
  2. Todd Veldhuizen: Techniques for Scientific C++: http://osl.iu.edu/~tveldhui/papers/techniques/techniques.html
  3. Linda Rising: Patterns Almanac 2000. Addison-Wesley, 2000
  4. Christopher Diggins: "C++ with Interfaces", C/C++ Users Journal, September 2004

Page 2 of 2

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel