0

I am trying to implement static cast. I need to check if the types T and U are implicitly convertible, if not check if one inherites from another. I can write a class to check each on of them, but I cant understand how to check implicit convert and if it doesnt compile check the inheritance.

all the checking need to on at compile time

shay
  • 1,211
  • 2
  • 8
  • 6
  • 3
    You want `is_convertible` and `is_constructible`; e.g. see "perfect initialization" in [N4064](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4064). – Kerrek SB Jun 17 '15 at 16:26
  • i can only use basic tools nothing that required and #include – shay Jun 17 '15 at 16:34
  • 3
    @shay: Then you'd better be writing a compiler.... otherwise all you're going to be doing for the next few weeks is reinventing half the standard library so that you can reinvent a built-in operator... – Lightness Races in Orbit Jun 17 '15 at 16:43
  • I got function f() that compiles if T and U are implicitly convertible and function g() that compiles if T inherits from U, but I don't know how to do "if f() doesnt compile try g()" – shay Jun 17 '15 at 16:50

1 Answers1

0

You could use type_traits and in particular std::is_convertible in combination with std::is_base_of:

template<typename T, typename U, typename std::enable_if<std::is_convertible<T, U>::value ||
std::is_base_of<T, U>::value>::type* = nullptr>
T mystatic_cast(U &u)
{
    return u;
}

Live Demo

101010
  • 41,839
  • 11
  • 94
  • 168