Search code examples
c++dynamic-cast

dynamic_cast not throwing exceptions as expected


Based on this answer...

Finding the type of an object in C++

...I wrote this code:

        static TVALUE getUpperBound()
        {
            SomeStruct<TVALUE>* t;

            try
            {
                dynamic_cast<SomeStruct<bool>*> (t);
                return 1;
            }
            catch (int e)
            {
            }

            try
            {
                dynamic_cast<SomeStruct<unsigned char>*> (t);
                return 255;
            }
            catch (int e)
            {
            }

            try
            {
                dynamic_cast<SomeStruct<unsigned int>*> (t);
                return 65535;
            }
            catch (int e)
            {
            }

            return 0;
        }

But it doesn't work :-/

I know there are OTHER ways to do this (using includes) but I need to get this technique working.

I can't include any includes in my code (it's a long story, but I simply can't)... hence this attempt at doing something that could be done easily with climits or typeinfo.

Can anyone please explain to me why this doesn't work?

Edit 1:

Thanks guys. I missed the reference vs pointer bit.

This works now:

template <typename TVALUE>
TVALUE getUpperBound()
{
    SomeStruct<TVALUE>* t;

    if (dynamic_cast<SomeStruct<bool>*> (t) != nullptr)
        return 1;
    if (dynamic_cast<SomeStruct<unsigned char>*> (t) != nullptr)
        return 255;
    if (dynamic_cast<SomeStruct<unsigned int>*> (t) != nullptr)
        return 65535;

    return 0;
}

Edit 2:

I tried @StilesCrisis advice and used template specialization

template <typename TVALUE>
TVALUE getUpperBound();

template <>
bool getUpperBound<bool>()
{
    return 1;
}

template <>
unsigned char getUpperBound<unsigned char>()
{
    return 255;
}

template <>
unsigned int getUpperBound<unsigned int>()
{
    return 65535;
}

Works a charm. Much better implementation. Thanks!


Solution

  • You are casting to a pointer. bad_cast is only generated when casting to a reference.

    You can just check for nullptr if casting to a reference isn't desirable.