1// DR 339 2// 3// Test of the use of casts with SFINAE 4 5// Boilerplate helpers 6typedef char yes_type; 7struct no_type { char data[2]; }; 8 9template<typename T> T create_a(); 10template<typename T> struct type { }; 11 12template<bool, typename T = void> struct enable_if { typedef T type; }; 13template<typename T> struct enable_if<false, T> { }; 14 15#define JOIN( X, Y ) DO_JOIN( X, Y ) 16#define DO_JOIN( X, Y ) DO_JOIN2(X,Y) 17#define DO_JOIN2( X, Y ) X##Y 18 19#define CHECK_CAST(CastKind) \ 20template<typename T, typename U> \ 21 typename enable_if<(sizeof((JOIN(CastKind,_cast)<U>(create_a<T>())), 0) > 0), \ 22 yes_type>::type \ 23 JOIN(check_,JOIN(CastKind,_cast))(int); \ 24 \ 25template<typename T, typename U> \ 26 no_type JOIN(check_,JOIN(CastKind,_cast))(...); \ 27 \ 28template<typename T, typename U> \ 29struct JOIN(has_,JOIN(CastKind,_cast)) \ 30{ \ 31 static const bool value = \ 32 (sizeof(JOIN(check_,JOIN(CastKind,_cast))<T, U>(0)) == sizeof(yes_type)); \ 33} 34 35template<typename T, typename U> 36typename enable_if<(sizeof(((U)create_a<T>()), 0) > 0), yes_type>::type 37 check_c_cast(int); 38 39template<typename T, typename U> no_type check_c_cast(...); 40 41template<typename T, typename U> 42struct has_c_cast 43{ 44 static const bool value = 45 (sizeof(check_c_cast<T, U>(0)) == sizeof(yes_type)); 46}; 47 48#ifdef __GXX_EXPERIMENTAL_CXX0X__ 49# define STATIC_ASSERT(Expr) static_assert(Expr, #Expr) 50#else 51# define STATIC_ASSERT(Expr) int JOIN(a,__LINE__)[Expr? 1 : -1] 52#endif 53 54CHECK_CAST(static); 55CHECK_CAST(dynamic); 56CHECK_CAST(const); 57CHECK_CAST(reinterpret); 58 59struct X { virtual void f(); }; 60struct Y { operator bool(); }; 61struct Z : public X { }; 62 63STATIC_ASSERT((has_static_cast<int, float>::value)); 64STATIC_ASSERT((!has_static_cast<X, Y>::value)); 65STATIC_ASSERT((has_static_cast<Z, X>::value)); 66 67STATIC_ASSERT(!(has_dynamic_cast<int, float>::value)); 68STATIC_ASSERT(!(has_dynamic_cast<X, Y>::value)); 69STATIC_ASSERT(!(has_dynamic_cast<X, Z>::value)); 70STATIC_ASSERT(!(has_dynamic_cast<Y, Z>::value)); 71STATIC_ASSERT((has_dynamic_cast<X*, Z*>::value)); 72STATIC_ASSERT((has_dynamic_cast<X*, Y*>::value)); 73STATIC_ASSERT(!(has_dynamic_cast<Y*, Z*>::value)); 74 75STATIC_ASSERT(!(has_const_cast<int, float>::value)); 76STATIC_ASSERT((has_const_cast<const int*, int*>::value)); 77STATIC_ASSERT((has_const_cast<int*, const int*>::value)); 78STATIC_ASSERT(!(has_const_cast<const int*, float*>::value)); 79 80STATIC_ASSERT((has_reinterpret_cast<int*, float*>::value)); 81STATIC_ASSERT(!(has_reinterpret_cast<void*, char>::value)); 82STATIC_ASSERT(!(has_reinterpret_cast<const X, X>::value)); 83 84STATIC_ASSERT((has_c_cast<int, float>::value)); 85STATIC_ASSERT(!(has_c_cast<X, Y>::value)); 86STATIC_ASSERT(!(has_c_cast<void*, char>::value)); 87