Class single function的partial template specialization,如何解决其他成员的undefined error

Class partial template specialization for single function, how to solve undefined error of other members

我有以下模板 class。我需要针对某些特定的 outT 案例专门化 alloc 函数。

template <typename inT, typename outT>
class Filter {
public:

  typedef inT  InputType;
  typedef outT OutputType;

  struct Options {
    int a, b, c;
  };

  virtual void alloc();

};



// Partial template specialization for SpecificOutputType
template < typename inT>
class Filter<inT, SpecificOutputType> {

  virtual void alloc();

};

这导致 Options class 和 OutputType 未为 gcc 定义,例如:

using FilterType = Filter<SomeIn, SpecificOutputType>:
FilterType::Options options;

结果

 error: ‘Options’ is not a member of `Filter<SomeIn, SpecificOutputType>`

如果我使用 SpecificOutputType 以外的其他类型,则不会发生此错误。

我该如何解决这个问题?

每个template specialization都是独立的,它们与主模板无关,因此您还必须在模板特化中明确定义OptionsOutputType和其他必要的成员。

Members of partial specializations are not related to the members of the primary template.

您可以创建一个公共基础 class 模板以避免代码重复。

template <typename inT, typename outT>
class FilterBase {
public:

  typedef inT  InputType;
  typedef outT OutputType;

  struct Options {
    int a, b, c;
  };

};

template <typename inT, typename outT>
class Filter : public FilterBase<inT, outT> {
public:
  virtual void alloc();
};


// Partial template specialization for SpecificOutputType
template <typename inT>
class Filter<inT, SpecificOutputType> : public FilterBase<inT, SpecificOutputType> {
  virtual void alloc();
};