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:
hasMaterial()
and hasDensity()
methods to the Voxel
class, to be overridden in derived classes.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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With