重载c ++模板类方法

Rob*_*rto 2 c++ templates class

我可以在扩展其专业化的类中重载模板类函数吗?

我有以下代码(我试图将其简化为最低限度):

#include <iostream>

using namespace std;

class X {
 public:
  unsigned test_x() {
    return 1;
  }
};

class Y {
 public:
  unsigned test_y() {
    return 2;
  }
};

template <typename T, typename U>
class A {

 public: 

  unsigned foo(U i) {
    cout << "A" << endl;   
    return i.test_x();
  }

  unsigned bar(T i) {
    return foo(i);
  }

};

class B : public A<Y, X> {
 public:
  unsigned foo(Y i) {
    cout << "B" << endl;   
    return i.test_y();
  }
};

int  main() {

  B b = B();
  Y y = Y();
  cout << "Hello: " << b.bar(y) << endl;   
  return 0;

}
Run Code Online (Sandbox Code Playgroud)

但是编译器会产生以下错误:

hello.cc: In member function ‘unsigned int A<T, U>::bar(T) [with T = Y, U = X]’:
hello.cc:47:   instantiated from here
hello.cc:30: error: no matching function for call to ‘A<Y, X>::foo(Y&)’
hello.cc:24: note: candidates are: unsigned int A<T, U>::foo(U) [with T = Y, U = X]
Run Code Online (Sandbox Code Playgroud)

基本上我想在派生类B中重载函数A :: foo().

ybu*_*ill 5

显然你所要求的是"静态多态",它是通过"奇怪的重复模板模式"来实现的:

template <typename Derived, typename T, typename U>
class A {
 public:

  unsigned foo(U i) {
    cout << "A" << endl;   
    return i.test_x();
  }

  unsigned bar(T i) {
    return static_cast<Derived*>(this)->foo(i);
  }

};

class B : public A<B, Y, X> {
 public:
  // Uncomment this line if you really want to overload foo
  // instead of overriding. It's optional in this specific case.
  //using A::foo; 

  unsigned foo(Y i) {
    cout << "B" << endl;   
    return i.test_y();
  }
};
Run Code Online (Sandbox Code Playgroud)