fork(1) download
  1. #include <assert.h>
  2.  
  3. // Helper to map any type to void, needed by SFINAE below
  4. template <typename T>
  5. struct void_type {
  6. typedef void type;
  7. };
  8.  
  9. // Selects a nested typedef or a default type D (using a macro to reduce boilerplate):
  10. #define SELECT_NESTED_TYPE( TYPE ) \
  11. template <typename T, typename D, typename _ = void> \
  12. struct select_##TYPE{ \
  13.   typedef D type; \
  14. }; \
  15. template <typename T, typename D> \
  16. struct select_##TYPE<T, D, typename void_type<typename T::TYPE>::type> { \
  17.   typedef typename T::TYPE type; \
  18. };
  19.  
  20. SELECT_NESTED_TYPE( int_t );
  21. SELECT_NESTED_TYPE( float_t );
  22. //...
  23. #undef SELECT_NESTED_TYPE
  24.  
  25. // Use
  26. template <typename T>
  27. class TheTemplate {
  28. public:
  29. typedef typename select_int_t<T,int>::type int_t;
  30. typedef typename select_float_t<T,double>::type float_t;
  31. //....
  32. };
  33.  
  34. // Test:
  35. template <typename T, typename U> struct same_type {
  36. static const bool value = false;
  37. };
  38. template <typename T> struct same_type<T,T> {
  39. static const bool value = true;
  40. };
  41. struct test1 {
  42. };
  43. struct test2 {
  44. typedef long long int_t;
  45. typedef float float_t;
  46. };
  47. int main() {
  48. // test1 has the default typedefs
  49. assert(( same_type< TheTemplate<test1>::int_t, int>::value ));
  50. assert(( same_type< TheTemplate<test1>::float_t, double>::value ));
  51. // test2 has the ones in the type
  52. assert(( same_type< TheTemplate<test2>::int_t, long long>::value ));
  53. assert(( same_type< TheTemplate<test2>::float_t, float>::value ));
  54. }
Success #stdin #stdout 0.02s 2720KB
stdin
Standard input is empty
stdout
Standard output is empty