【问题标题】:Alternatives to CRTPCRTP 的替代品
【发布时间】:2015-10-06 13:45:42
【问题描述】:

假设我们有 virtual method 的以下类:

struct icountable{
   virtual int count() = 0;

   bool empty(){
      return count() == 0;
   }
}

struct list : public icountable {
...
}

现在假设这可以用CRTP 重写。应该看起来或多或少像:

template <typename T> 
struct icountable{
   bool empty(){
      return static_cast<T*>(this)->count() == 0;
   }
}

struct list : public icountable<list> {
...
}

现在假设类本身不需要使用 empty() 方法。然后我们可以这样做:

template <typename T> 
struct icountable : public T{
   bool empty(){
      return count() == 0;
   }
}

struct list_base{
...
}

typedef icountable<list_base> list;

我的问题是第三个例子。这就是所谓的traits吗?如果我使用这些有优点/缺点吗?

【问题讨论】:

  • 不,这不是特质。
  • 那么它是什么,所以我可以用谷歌搜索它......
  • 它可能(并且现在)被称为“mixin”,这是一个存在于较旧的 OO 语言中的术语,似乎也适用于此。不知道有没有更好的名字。

标签: c++ traits virtual-functions crtp


【解决方案1】:

正如cmets所说,这是混入概念,您可以找到有关它的信息here

特质不同,here你可以找到一个基本的例子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 2012-01-25
    • 2015-08-05
    • 2011-01-01
    • 2011-10-24
    相关资源
    最近更新 更多