Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ find out if a variable is a reference or pointer

Tags:

c++

macros

I have a macro in the catch section of code, say

#define CATCH( doSomething )           \
    catch (MyException& e)             \
    {                                  \
        try                            \
        {                              \
            doSomething;               \
        }                              \
    }                                  \
    catch (MyException* e)             \
    {                                  \
        try                            \
        {                              \
            doSomething;               \
        }                              \
    }                         

and in the doSomething section I need to get to the contents of an exception, is there a way to do this? Some function isPointer that can be used like this:

try
{
    THROW(new MyException());
}
CATCH(                                 \
    if( isPointer(e) )                 \
    {                                  \
        std::cout << (*e).toString();  \
    }                                  \
    else                               \
    {                                  \
        std::cout << e.toString();     \
    }                                  \
)
like image 229
sukhmel Avatar asked Dec 30 '11 10:12

sukhmel


1 Answers

Just use overloading to possibly dereference the argument:

template<class T>
T& deref(T* p) { return *p; }

template<class T>
T& deref(T& r) { return r; }

And use that:

CATCH(                                 \
    std::cout << deref(e).toString();  \
)

Though I have to admit I see no reason to dynamically allocate exception objects.

like image 165
Xeo Avatar answered Sep 30 '22 00:09

Xeo