模板元编程。 class 成员有条件存在

Template metaprogramming. Conditional existence for class members

我想知道是否可以编写一个模板 class,在其编译版本中设置不同的成员。

例如继承是如何实现的:

/// These statistics are supported for all data types
struct StatsBase {
  size_t count;

  virtual void Describe() { print(count); }
};

/// These can describe almost all data types, but not all of them
template<DataType data_type>
struct StatsMinMax : public StatsBase {
  CppType<data_type> min;
  CppType<data_type> max;

  void Describe() override {
    StatsBase::Describe();
    print(min);
    print(max);
  }
};

/// These are for numeric data types only
template<DataType data_type>
struct StatsAll : public StatsMinMax<data_type> {
  CppType<data_type> sum;

  void Describe() override {
    StatsMinMax<data_type>::Describe();
    print(sum);
  }
}

而且,假设我有以下 constexpr 函数

constexpr bool IsMinMaxSupported(data_type dt) { /* details */ }
constexpr bool IsSumSupported(data_type dt) { /* details */ }

所以,问题是是否可以用 C++ 表达这样的东西:

template<DataType data_type>
struct Stats {
  size_t count;
  CppType<data_type> min; // Must exist only in those instances, where IsMinMaxSupported(data_type) == true
  CppType<data_type> max; // Must exist only in those instances, where IsMinMaxSupported(data_type) == true
  CppType<data_type> sum; // Must exist only in those instances, where IsSumSupported(data_type) == true

  void Describe() { 
    print(count);
    if (IsMinMaxSupported(data_type)) {
      print(min);
      print(max);
    }
    if (IsSumSupported(data_type)) {
      print(sum);
    }
  }
};

意味着某些字段在某些情况下不能物理存在(这对内存消耗至关重要)。如果可能的话,方法 Describe() 会像我写的那样编译,还是应该使用 SFINAE 重写(使用适当的专业化)?

可以通过模板特化来实现:

template<typename DataType, bool x_min_max_supported> struct
StatsMinMax { /* empty */ };

template<typename DataType> struct
StatsMinMax<DataType , true>
{
    DataType min;
    DataType max;
};

...

template<DataType data_type>
struct Stats
: public StatsMinMax<DataType, IsMinMaxSupported(data_type)>
{