c++ - 单函数的类部分模板特化,如何解决其他成员的未定义错误

标签 c++ templates template-specialization partial-specialization

我有以下模板类。我需要为某些特定的 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 类和 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.

您可以创建一个公共(public)基类模板以避免代码重复。

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

关于c++ - 单函数的类部分模板特化,如何解决其他成员的未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39959807/

相关文章:

基类型的 C++ 模板继承问题

c++ - 同一函数的模板化和非模板化版本是否被视为重载?

c++ - 短程序错误。 C++ 新手,Adafruit LED 灯条,Arduino

c++ - 指向成员的指针作为模板参数

c++ - 编译器选择专门用于数组的预期模板,但随后尝试将数组参数转换为指针

C++:模板特化,std 映射选择了错误的特化

c++ - 如何为 C++ 创建命令行模拟器 GUI

android - 使用带有 Android NDK 的 OpenCV 转换数据格式

c++ - 避免在消息传递中向下转型的设计模式

c++ - 实例化和未实例化模板的部分模板特化