[英]C++ Mixin using derived types
我如何將 class 中的 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
在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.
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.