2

static constexprC++ で派生型を強制的に定義する方法はありますか? 基本クラスがあり、すべての派生クラスにstatic const bool has_property.

私はCRTPでこれをやってみました(各派生クラスが独自のものを取得するようにstatic const):

template <typename T, class MyClass>
struct Base {
    T data;
    static constexpr bool has_property;
};

template <typename T>
struct Derived : public Base<T, Derived<T> > {
    static constexpr bool has_property = false;
};

しかし、コンパイラBase::has_propertyは初期化されていないと文句を言います。

どうすればこれを達成できますか?

4

2 に答える 2

2

基本テンプレートのパラメータに has_property 値を追加するとうまくいくかもしれません:

template <typename T, class MyClass, bool hasPropertyValue>
struct Base {
    T data;
    static constexpr bool has_property = hasPropertyValue;
};

template <typename T>
struct Derived : public Base<T, Derived<T>, false > {
};

[UPDATE1] 配列の場合、単一のブール値を渡す代わりに、値を含む構造体を渡します。

template <typename T, class MyClass, class MyClassPropertyValues>
struct Base {
    T data;
    static constexpr bool has_property[MyClassPropertyValues::length];
};
template <typename T, class MyClass, class MyClassPropertyValues>
constexpr bool Base<T, MyClass, MyClassPropertyValues>::
 has_property[MyClassPropertyValues::length] = MyClassPropertyValues::initValues;

struct DerivedPropertyValues {
   static constexpr size_t length = 3;
   static constexpr bool initValues[length];
};    
constexpr bool DerivedPropertyValues::initValues[length] = { true, false, true };

template <typename T>
struct Derived : public Base<T, Derived<T>, DerivedPropertyValues > {
};
于 2012-07-08T10:55:23.663 に答える