fork download
  1. #include <stdio.h>
  2.  
  3. #define INTERFACE(Name) \
  4. template <typename ImplType> \
  5. struct Name
  6.  
  7. #define INTERFACE_FUNC(Ret, Name, Args) \
  8. template <typename... TArgs> \
  9. inline Ret Name (TArgs... args) { \
  10.   static constexpr Ret (ImplType::*ptr) Args = &ImplType::Name; \
  11.   return ((static_cast<ImplType *>(this))->*ptr)(args...); \
  12. }
  13.  
  14. INTERFACE(Iface) {
  15. INTERFACE_FUNC(int, Foo, (int x, int y))
  16. INTERFACE_FUNC(void, Bar, (double a))
  17. };
  18.  
  19. struct Impl : Iface<Impl> {
  20. int Foo (int x, int y)
  21. {
  22. return x + y;
  23. }
  24.  
  25. void Bar (double a)
  26. {
  27. printf("%f\n", a);
  28. }
  29.  
  30. void NotExposed ()
  31. {
  32. }
  33. };
  34.  
  35. template <typename ImplType>
  36. void UseViaIface (Iface<ImplType> *iface)
  37. {
  38. int res = iface->Foo(2, 4);
  39. printf("%d\n", res);
  40.  
  41. iface->Bar(3.4);
  42.  
  43. // Compile error because NotExposed is not part of the interface.
  44. //iface->NotExposed();
  45. }
  46.  
  47. int main ()
  48. {
  49. Impl impl;
  50. UseViaIface(&impl);
  51. return 0;
  52. }
  53.  
  54.  
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
6
3.400000