我有以下模板类。我需要为某些特定的 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是独立的,它们与主模板无关,因此您还必须在模板特化中明确定义 Options
、OutputType
和其他必要成员。
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/