c++ - 纯虚函数的模板特化

标签 c++ templates virtual-functions

我如何专门化在基类中定义为纯函数的模板化函数?

struct A {
    virtual void func(int a) = 0;
    //virtual void func(int a) {} // replace above line with this and it works
};

struct B : public A {
    template<typename T> void func(T t) {
        cout <<"hello"<<endl;
    }
};
template<> void B::func<int>(int a) { cout <<"hello 2"<<endl; }


int main() {
    B b;
    b.func(2);
}

错误:

error: variable type 'B' is an abstract class B b; ^ note: unimplemented pure virtual method 'func' in 'B' virtual void func(int a) = 0;

最佳答案

虚函数只能被非模板函数覆盖。在这种情况下,

Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).

注意函数模板不能是virtual functions ;

Functions templates cannot be declared virtual.

来自标准,[temp.mem]/4

A specialization of a member function template does not override a virtual function from a base class. [ Example:

class B {
  virtual void f(int);
};

class D : public B {
  template <class T> void f(T); // does not override B​::​f(int)
  void f(int i) { f<>(i); }     // overriding function that calls the template instantiation
};

— end example ]

关于你的问题,

why it works if the function is made 'not pure'?

编译错误消失了,但它仍然没有像你预期的那样工作;派生类中的函数模板不会覆盖基类的虚函数。你可以用 dynamic dispatch 查看:

If a derived class is handled using pointer or reference to the base class, a call to an overridden virtual function would invoke the behavior defined in the derived class.

请注意,您应该使用指针或引用来使动态调度工作,例如

B b;
A* pa = &b;
pa->func(2);

LIVE

您也可以申请override specifier帮助您确认覆盖

关于c++ - 纯虚函数的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56954318/

相关文章:

python - .css 不会影响我在 django 中的模板

c++ - 模板 friend 和嵌套类

c# - 如何重写具有 out 参数的虚拟方法?

c++ - 运算符 << 重载

c++ - 从 C++ 方法调用 Objective-C 方法? [2]

c++ - 在 Qt 中逐行读取文本文件

c++ - 什么时候应该限制派生类中虚函数的可访问性?

c++ - 测试执行后缺少某些 GCDA 文件

c++ - 传递具有依赖嵌套参数类型的模板模板参数时出错

c++ - 如何使继承的虚函数不可用?