c++ - 使用派生类型的C++ Mixin

标签 c++ mixins crtp

如何将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;
};
lang语语义问题:
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

最佳答案

在实例化Mixin<DerivedInt>时,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.
};

关于c++ - 使用派生类型的C++ Mixin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64526361/

相关文章:

typescript - 在 TypeScript 中通过装饰器向类添加属性

C++:混入和多态性

python - 在进行 South 数据迁移时,如何访问 Django 模型的 mixin 方法?

c++ - 在模板化类型的 CRTP 中定义类型

c++ - 基于重载构造函数的策略类模板参数选择

c++ - Mysql截断难读字符

c++ - C++线程。为什么总是执行最后一个线程?

c++ - 使用 Qt、Wt 或 NaCl 构建框架?

c++ - 使用 for as while with counter

C++ CRTP 和不完整的类定义