#include <iostream>
class Base {
public:
virtual int fun() = 0;
virtual int fun(int a) = 0;
};
namespace module_teplate {
template < typename T>
int fun(Base* ptr) {
return dynamic_cast<T*>(ptr)->fun();
}
template < typename T>
int fun(Base* ptr, int a) {
return dynamic_cast<T*>(ptr)->fun(a);
}
}
class A : public Base {
public:
virtual int fun() {std::cout << "A" << std::endl; return 0;};
virtual int fun(int a) {std::cout << "A" << a << std::endl; return 0;};
};
namespace B {
class B : public A {
public:
B(){};
virtual int fun() {std::cout << "B" << std::endl; return 0;}
//virtual int fun(int a) {std::cout << "B" << a << std::endl; return 0;};
};
int fun(Base* ptr) {
return module_teplate::fun<B>(ptr);
}
int fun(Base* ptr, int a) {
return module_teplate::fun<B>(ptr, a);
}
}
namespace B {
}
int main() {
Base* ptr = new B::B;
B::fun(ptr);
B::fun(ptr, 5);
return 0;
}
上面代码中, 取消class B中的注释,能够成功编译、运行且输出正确结果。
不取消,则会报错
main.cpp: In instantiation of ‘int module_teplate::fun(Base*, int) [with T = B::B]’:
main.cpp:48:45: required from here
main.cpp:25:44: error: no matching function for call to ‘B::B::fun(int&)’
return dynamic_cast<T*>(ptr)->fun(a);
^
main.cpp:41:17: note: candidate: virtual int B::B::fun()
virtual int fun() {std::cout << "B" << std::endl; return 0;}
^~~
main.cpp:41:17: note: candidate expects 0 arguments, 1 provided
什么原因?
- 来自「最水木 for iPhone13,2」
--
FROM 223.104.39.*