如何将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/