我有两个类(class):
struct A {
template <typename T>
void print(T& t){
// do sth specific for A
}
};
struct B : A {
template <typename T>
void print(T& t){
// do sth specific for B
}
};
在这种情况下,无法编译具有虚函数(A 和 B 都继承自)的更通用的基类,因为模板没有虚函数。当我尝试将所有 A 或 B 对象一般委托(delegate)给同一“接口(interface)”时,有没有人有解决此类问题的想法?先感谢您。
真诚的, 君
最佳答案
可以考虑使用using CRTP .
template<typename Derived>
struct Base {
template <typename T>
void print(T& t){
static_cast<Derived*>(this)->print(t);
}
};
struct A : Base<A> {
// template print
};
struct B : Base<B> {
// template print
};
示例用法:
template<typename T, typename ARG>
void foo (Base<T>* p, ARG &a)
{
p->print(a);
}
这个方法将被调用为,
foo(pA, i); // pA is A*, i is int
foo(pB, d); // pB is B*, d is double
这里是 another demo code .
关于c++ - looking for c++ member function override (non virtual) 解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6784893/