Comparing types in C++

139 Views Asked by At

I'm working on a custom engine where I have 2 different transform classes, one for 2D and one for 3D. I'm using a #define to choose which transform class to use and using that definition instead of the classname in places where the logic should be the same. I am at a part now where I want them to have different logic and wanted to do a comparison to branch off for that. What do I need to do to get this to work?

class Transform2D;
class Transform3D;

#define TransformClass Transform2D

if(TransformClass == Transform2D)
{
  //like this
}
else    
{
  //like that
}

Type id worked for that. How do you handle?

if ( typeid(TransformClass) == typeid(Transform2D) )
{
    ittransform->SetRotation(0);
    ittransform->SetScale(Vector2D(defaultScale, defaultScale));
}
else
{
    ittransform->SetRotation(Vector3f());
    ittransform->SetScale(Vector3f(defaultScale, defaultScale, defaultScale));
}
3

There are 3 best solutions below

4
On

Use function decomposition (break your logic into sub-functions) and then make use of overloading.

void do_something(Transform2D const& t) {
  ...
}

void do_something(Transform3D const& t) {
  ...
}

void test() {
  TransformClass tc = ...
  do_something(tc); // invokes the desired overload
}

Also, use a typedef or type alias instead of a define, e.g.

#if defined(USE_3D)
using TransformClass = Transform3D;
#else
using TransformClass = Transform2D;
#endif

You can also define the alias via std::conditional and be even more functional-y and C++-y.

3
On

I think the easiest option is to create an extra define, something like this:

#define USING_CLASS_2D 1

#if USING_CLASS_2D
#define TransformClass Transform2D
#else
#define TransformClass Transform3D
#endif

if (USING_CLASS_2D)
{
}
else
{
}
0
On

Do not use if() in this situation.

Since you're coding with the pre-processor, stick with it:

# if USING_3D
    3d code
# else
    2d code
# endif

and if you strive to keep most of the methods and ancilliary classes looking broadly the same, you'll probably manage to avoid too much use of #if

Old C code was littered with this stuff, and it was considered good. However nowadays, it's very old fashioned. Think thrice before you continue down this path.