我无法实现以下功能:
class Based {
public:
template <typename T> void foo(T t) { boo(t); }
template <typename T> virtual void boo(T t) = 0; // Error!
};
class Derived : public Based {
public:
template <typename T> void boo(T t) {
std::cout<<"Derived::boo called\n";
}
};
int main() {
Derived derived;
derived.foo(0);
derived.foo('c');
//etc.
}
我知道C ++不允许使用虚拟模板化方法,但看不到任何其他方法来执行此操作。 任何帮助将不胜感激!
答案 0 :(得分:0)
出于我的目的,我找到了这个解决方案。
template <typename X>
class Based {
public:
template <typename T> void foo(T t) { static_cast<X *>(this)->boo(t); }
};
class Derived : public Based<Derived> {
public:
template <typename T> void boo(T t) {
std::cout<<"Derived::boo called\n";
}
};
int main() {
Derived derived;
derived.foo(0);
derived.foo('c');
//etc.
}
感谢您的建议!