使用派生类型的C ++ Mixin

问题描述

如何将typedef从类传递到其mixin?起初我以为可能是在命名冲突,但是在mixin中重命名public interface UserRepository extends JpaRepository<User,Integer> { User findByBarcode(String barcode); List <User> findByQty(int qty); } 也无济于事。

value_t

c语语义问题:

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;
};

解决方法

在实例化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.
};