类型traits vs静态成员的优点? [英] Advantages of type traits vs static members?

查看:143
本文介绍了类型traits vs静态成员的优点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类( Voxel ),子类可能有或没有多个不同的属性(材质,密度等)与get和set方法。现在,我要写如下的一些代码:

  template< typename VoxelType> 
void process(VoxelType voxel)
{
if(VOXEL_HAS_MATERIAL)
{
//做一些涉及调用get / setMaterial()的工作
}
if(VOXEL_HAS_DENSITY)
{
//做一些涉及调用get / setDensity()的工作
}
}

因此我想实现 VOXEL_HAS_MATERIAL VOXEL_HAS_DENSITY parts。两个简单的选项是:


  1. 添加静态 hasMaterial() hasDensity()方法到 Voxel 类,以在派生类中覆盖。

  2. 创建具有 hasMaterial() hasDensity()的类型traits类,使用方法(2)允许为基本类型定义traits(int,voxel,voxel)。

  3. 等等),但这在我的情况下没有用。在这里使用type traits还有什么优点吗?或者我应该去更简单的静态方法吗?



    注意:我将分别考虑基于SFINAE的方法。



    Edit1:我更改了示例代码以显示模板的使用。我正在寻找这个问题的静态而不是运行时解决方案。理想情况下,如果编译器确定它们不能对给定类型执行,则编译器将能够清除if语句中的代码。

    解决方案

    Type-traits非常有用,因为即使不能更改类型本身,它们也可以轻松地添加到类型中。另外,使用type-traits你可以简单地提供一个明智的默认(例如,你可以委托 hasMaterial hasDensity 到类的合适的静态成员),然后你只需要专门针对不使用默认的类的trait。


    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.

    解决方案

    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.

    这篇关于类型traits vs静态成员的优点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆