code_junkie

Compile-time type based dispatch

Nov 11th, 2011
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. template<class T, template <class> class Manager = DefaultManager> class Data
  2. {
  3. private:
  4. T *data_;
  5.  
  6. public:
  7. void Dispatch()
  8. {
  9. if(SUPERSUBCLASS(Container, T))
  10. {
  11. data_->IKnowThisIsHere();
  12. }
  13. else
  14. {
  15. Manager<T>::SomeGenericFunction(data_);
  16. }
  17. }
  18. }
  19.  
  20. private:
  21. int *data_;
  22.  
  23. public:
  24. void Dispatch()
  25. {
  26. if(false)
  27. {
  28. data_->IKnowThisIsHere();
  29.  
  30. void Dispatch()
  31. {
  32. if(false)
  33. {
  34. dynamic_cast<Container*>(data_)->IKnowThisIsHere();
  35.  
  36. error: cannot dynamic_cast '((const Data<double, DefaultManager>*)this)->Data<double, DefaultManager>::data_' (of type 'double* const') to type 'class Container*' (source is not a pointer to class)
  37. error: cannot dynamic_cast '((const Data<std::string, DefaultManager>*)this)->Da<sttad::string, DefaultManager>::data_' (of type 'struct std::string* const') to type 'class Container*' (source type is not polymorphic)
  38.  
  39. template <bool n>
  40. struct int2type
  41. { enum { value = n}; };
  42.  
  43. #include <iostream>
  44.  
  45. #define MACRO() true // <- macro used to dispatch
  46.  
  47. template <bool n>
  48. struct int2type
  49. { enum { value = n }; };
  50.  
  51. void method(int2type<false>)
  52. { std::cout << __PRETTY_FUNCTION__ << std::endl; }
  53.  
  54. void method(int2type<true>)
  55. { std::cout << __PRETTY_FUNCTION__ << std::endl; }
  56.  
  57. int
  58. main(int argc, char *argv[])
  59. {
  60. // MACRO() determines which function to call
  61. //
  62.  
  63. method( int2type<MACRO()>());
  64.  
  65. return 0;
  66. }
  67.  
  68. void Dispatch()
  69. {
  70. myfunc(data_);
  71. }
  72.  
  73. private:
  74.  
  75. // EDIT: disabled the default case where the specialisation matched
  76. template <typename U>
  77. typename enable_if_c<is_base_of<Container, U>::value, U>::type myfunc(U& data_) {
  78. data_->IKnowThisIsHere();
  79. }
  80.  
  81. template <typename U>
  82. typename disable_if_c<is_base_of<Container, U>::value, U>::type myfunc(U& data_) { // default case
  83. Manager<U>::SomeGenericFunction(data_);
  84. }
  85.  
  86. error: cannot dynamic_cast '((const Data<double, DefaultManager>*)this)->Data<double, RawManager>::data_' (of type 'double* const') to type 'class Container*' (source is not a pointer to class)
  87.  
  88. error: cannot dynamic_cast '((const Data<std::string, DefaultRawManager>*)this)->Data<std::string, DefaultManager>::data_' (of type 'struct std::string* const') to type 'class Container*' (source type is not polymorphic)
Add Comment
Please, Sign In to add comment