CRTP的替代方案

Alternatives to CRTP

本文关键字:方案 CRTP      更新时间:2023-10-16

假设我们有以下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吗?如果我使用这些有什么优点/缺点吗?

正如评论所说,这是混合的概念,您可以在这里找到有关它的信息。

特征是不同的,在这里你可以找到一个基本的例子。