fork(2) download
  1. #include <iostream>
  2. #include <utility>
  3. #include <type_traits>
  4.  
  5. namespace details {
  6. template<class...>struct types{using type=types;};
  7. template<class U, class Types, class=void>
  8. struct smart_cast_t:std::false_type {
  9. using type=U;
  10. template<class A>
  11. U operator()(A&& a)const{return std::forward<A>(a);}
  12. };
  13. template<class U, class T0, class...Ts>
  14. struct smart_cast_t<
  15. U, types<T0, Ts...>,
  16. typename std::enable_if<std::is_convertible<U, T0>::value>::type
  17. >:std::true_type
  18. {
  19. using type=T0;
  20. template<class A>
  21. T0 operator()(A&& a)const{return std::forward<A>(a);}
  22. };
  23. template<class U, class T0, class...Ts>
  24. struct smart_cast_t<
  25. U, types<T0, Ts...>,
  26. typename std::enable_if<!std::is_convertible<U, T0>::value>::type
  27. >:smart_cast_t< U, types<Ts...> >
  28. {};
  29. }
  30.  
  31. template<class... Ts, class U>
  32. auto smart_cast( U&& u )
  33. -> decltype(details::smart_cast_t< U, details::types<Ts...> >{}( std::forward<U>(u) ))
  34. {
  35. return details::smart_cast_t< U, details::types<Ts...> >{}( std::forward<U>(u) );
  36. }
  37.  
  38. int main() {
  39. std::cout << smart_cast< char, double >( int('a') ) << "\n";
  40. std::cout << smart_cast< double, char >( int('a') ) << "\n";
  41. // your code goes here
  42. return 0;
  43. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
a
97