Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of type traits vs static members?

I have a class (Voxel) with subclasses which may or may not have a number of different properties (material, density, etc) with get and set methods. Now, I want to write some code as follows:

template <typename VoxelType>
void process(VoxelType voxel)
{
  if(VOXEL_HAS_MATERIAL)
  {
    //Do some work which involves calling get/setMaterial()
  }
  if(VOXEL_HAS_DENSITY)
  {
    //Do some work which involves calling get/setDensity()
  }
}

I would therefore like to implement the VOXEL_HAS_MATERIAL and VOXEL_HAS_DENSITY parts. Two simple options are:

  1. Add static hasMaterial() and hasDensity() methods to the Voxel class, to be overridden in derived classes.
  2. Create a type traits class with hasMaterial() and hasDensity(), and specialize this for each Voxel subclass.

Using method (2) allows the traits to be defined for primitive types (int, etc) but this is not useful in my case. Are there any further advantages to using type traits here or should I go for the simpler static method approach?

Note: I'm also aware of SFINAE based approaches which I shall consider separately.

Edit1: I've changed the sample code to show the use of templates. I'm looking for static rather than runtime solutions to this problem. Ideally, the compiler would be able to strip out the code in the if statements if it determines they can not be executed for the given type.

like image 432
David Williams Avatar asked Sep 08 '25 14:09

David Williams


1 Answers

Type-traits are useful because they can easily be added to types even if you cannot change the type itself. Also, using type-traits you can simply provide a sensible default (for instance, you can just delegate hasMaterial and hasDensity to appropriate static members of the class), and then you just have to specialize the trait for classes that do not work with this default.

like image 66
Björn Pollex Avatar answered Sep 10 '25 05:09

Björn Pollex