Can a class member function template be virtual?

前端 未结 13 1232
旧时难觅i
旧时难觅i 2020-11-22 03:29

I have heard that C++ class member function templates can\'t be virtual. Is this true?

If they can be virtual, what is an example of a scenario in which one would

13条回答
  •  忘掉有多难
    2020-11-22 04:14

    No they can't. But:

    template
    class Foo {
    public:
      template
      void f(const P& p) {
        ((T*)this)->f

    (p); } }; class Bar : public Foo { public: template void f(const P& p) { std::cout << p << std::endl; } }; int main() { Bar bar; Bar *pbar = &bar; pbar -> f(1); Foo *pfoo = &bar; pfoo -> f(1); };

    has much the same effect if all you want to do is have a common interface and defer implementation to subclasses.

提交回复
热议问题