How to test casting time?

70 views Asked by At

In an assignment, I have been asked to create my own static_cast and dynamic_cast using templates specialization. How do I test that my static casts are really done compile-time and dynamic casts on run-time?

template<typename Dst, typename Src>
static Dst my_static_cast(Src src);

template<typename Dst, typename Src>
static Dst my_dynamic_cast(Src src);
1

There are 1 answers

0
matb On

Not a full answer but consider this:

class D
{
public:
    virtual ~D(){}
};
class A : public D{};

class B{};

Now dynamic_cast<B*>(new A()) compiles OK (and returns 0) but static_cast<B*>(new A()) results in a compilation error. I'm almost sure you can SFINAE this to make an appropriate test.

Of course, this test assumes you only need to differentiate between 100% standard-compliant static_cast and 100% standard-compliant dynamic_cast. For detecting bugs in your implementation additional tests are needed.

EDIT: You cannot fully test it automatically. Casts require runtime arguments and so they cannot be tested at compile time. And, at runtime, the only difference between compile-time calculated thing and runtime-calculated thing is performance. I wouldn't recommend testing by "well, runtime casts can't be that fast". It just isn't reliable.