c++ - 在派生类模板中专门化基类的成员函数

标签 c++ templates specialization

看看这段代码:

struct foo {
    virtual int bleh() {
        return 42;
    }
};


template<typename T>
struct bar : public foo {

};

// ERROR
template<>
int bar<char>::bleh() {
    return 12;
}

我正在尝试提供 base::bleh 的定义仅适用于 bar<char> , 但编译器 (gcc 4.7.2) rejects我的代码具有以下诊断:

template-id ‘bleh<>’ for ‘int bar<char>::bleh()’ does not match any template declaration

好像base::bleh以某种方式隐藏在 bar 中.我已经使用 bar 中的以下定义修复了此问题:

template<typename T>
struct bar : public foo {
    // doesn't work
    //using foo::bleh; 

    // this works
    int bleh() {
        return foo::bleh();
    }
};

但我很好奇为什么编译失败。为什么编译器拒绝我的代码?

最佳答案

在您的非编译示例中,您试图专门化和定义一个尚未在 bar 的模板定义中声明的函数......在您后面的示例中,您实际上已经声明了以及在 bar 的模板定义中定义函数的非专用版本,这就是它编译的原因。据我所知,这是标准中有关第一个版本无法编译 (14.7.3/4) 的原因的相关语言:

A member function, a member function template, a member class, a member enumeration, a member class template, or a static data member of a class template may be explicitly specialized for a class specialization that is implicitly instantiated; in this case, the definition of the class template shall precede the explicit specialization for the member of the class template

关于c++ - 在派生类模板中专门化基类的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16473499/

相关文章:

c++ - 智能指针能否有选择地隐藏或重定向函数调用到它们正在包装的对象?

c++ - 未知的方法语法

c++ - 是否有可能让可执行文件在特定日期后不运行?

C++静态非成员函数返回模板类的对象

c++ - (重新)命名 std::pair 成员

c++ - 部分特化可变参数模板类型名为 void

c++ - KDE 贡献

c++ - 排除一种类型的模板

c++ - 概念的重载/特化

C++:扩展模板类