使用派生类型的 C++ Mixin
C++ Mixin using derived types
如何将 typedef 从 class 传递到它的 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
在实例化 Mixin<DerivedInt>
时,DerivedInt
是一个不完整的 class - 编译器还没有看到 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.
};
如何将 typedef 从 class 传递到它的 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
在实例化 Mixin<DerivedInt>
时,DerivedInt
是一个不完整的 class - 编译器还没有看到 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.
};