【问题标题】:C++ Mixin using derived types使用派生类型的 C++ Mixin
【发布时间】:2020-10-25 16:54:24
【问题描述】:

如何将 typedef 从一个类传递给它的 mixin?起初我以为可能是命名冲突,但在 mixin 中重命名 value_t 也无济于事。

template <typename Derived>
class Mixin
{
public:
    using value_t = typename Derived::value_t;
    
    Derived * self()
    {
        return static_cast<Derived *>(this);
    }
    
    value_t x() const
    {
        return self()->x;
    }
};

class DerivedInt : public Mixin<DerivedInt>
{
public:
    using value_t = int;
    value_t x = 0;
};

class DerivedDouble : public Mixin<DerivedDouble>
{
public:
    using value_t = double;
    value_t x = 0.0;
};

clang 语义问题:

file.h:14:39: error: no type named 'value_t' in 'DerivedInt'
file.h:27:27: note: in instantiation of template class 'Mixin<DerivedInt>' requested here

file.h:14:39: error: no type named 'value_t' in 'DerivedDouble'
file.h:34:30: note: in instantiation of template class 'Mixin<DerivedDouble>' requested here

【问题讨论】:

    标签: c++ mixins crtp


    【解决方案1】:

    Mixin&lt;DerivedInt&gt; 被实例化时,DerivedInt 是一个不完整的类——编译器在class DerivedInt 之外没有看到任何它。这就是无法识别DerivedInt::value_t 的原因。

    大概是这样的:

    template <typename Derived, typename ValueType>
    class Mixin
    {
    public:
        using value_t = ValueType;
    };
    
    class DerivedInt : public Mixin<DerivedInt, int> {
      // doesn't need its own `value_t` typedef.
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多