fork(2) download
  1. //User types
  2. struct field_t{};
  3. struct other_t{};
  4. struct StructA{field_t field;};
  5. struct StructB{other_t other;};
  6. struct StructC:public StructA{};
  7. struct StructD:public StructB{};
  8. struct StructT{other_t field;field_t other;};
  9. //Implementation detail
  10. template<typename T,typename FIELD_T>
  11. struct type_has_field{
  12. struct Fallback {FIELD_T field;};
  13. struct Derived:T,Fallback{};
  14. template<typename C, C> struct ChT;
  15. template<typename C> static char (&f(ChT<FIELD_T Fallback::*, &C::field>*))[1];
  16. template<typename C> static char (&f(...))[2];
  17.  
  18. static bool const value = sizeof(f<Derived>(0)) == 2;
  19. };
  20. //Experiment
  21. void UnitTest(){
  22. static_assert(
  23. true==type_has_field<StructA,field_t>::value,
  24. "field_t StructA::field - should exist"
  25. );
  26. static_assert(
  27. false==type_has_field<StructB,field_t>::value,
  28. "field_t StructB::field - should not exist"
  29. );
  30. static_assert(
  31. true==type_has_field<StructC,field_t>::value,
  32. "field_t StructC::field - should exist"
  33. );
  34. static_assert(
  35. false==type_has_field<StructD,field_t>::value,
  36. "field_t StructD::field - should not exist"
  37. );
  38. static_assert(
  39. false==type_has_field<StructT,field_t>::value,
  40. "field_t StructT::field - should not exist"
  41. );
  42. static_assert(
  43. true==type_has_field<StructT,other_t>::value,
  44. "other_t StructT::field - should exist"
  45. );
  46. }
  47. int main(){return 0;}
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘void UnitTest()’:
prog.cpp:38:3: error: static assertion failed: field_t StructT::field - should not exist
   static_assert(
   ^
stdout
Standard output is empty