模板元编程。班级成员的条件存在

时间:2018-04-24 10:26:57

标签: c++ c++11 template-meta-programming sfinae

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

例如,如何使用继承实现它:

/// 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重写(使用适当的专业化)?

1 个答案:

答案 0 :(得分:5)

可以通过模板专业化来实现:

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)>
{
相关问题