获取错误默认模板参数可能不会在函数模板中使用

Getting error default template arguments may not be used in function templates

本文关键字:函数模板 默认 取错误 参数 获取      更新时间:2023-10-16

我有一个带有默认模板参数的模板类。我在编译此代码时收到"函数模板中可能无法在函数模板中使用默认模板参数"错误,用于定义MyClass<T, n>::empty()。我正在 gcc 版本 4.2.4(ubuntu 10)上编译代码:

template<typename T, int n=10>
class MyClass{
    T Val[n];
    int Capacity;
    int Size;
    public:
    MyClass():Capacity(n), Size(0) {}
    bool empty();
};
template<typename T, int n=10>
bool MyClass<T, n>::empty() {
    return Size?false:true;
}

假设问题是如何使代码编译,则可以从empty()实现的模板参数列表中删除默认值:

template<typename T, int n>
bool MyClass<T, n>::empty() {
  return Size ? false : true;
}

请注意,需要在MyClass<T>实例中调用empty()的代码必须可以访问该实现。它不能在实现文件中编译。