c++ - looking for c++ member function override (non virtual) 解决方案

标签 c++ inheritance overriding

我有两个类(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/

相关文章:

typescript - 覆盖 TypeScript 中接口(interface)的属性

java - 修改 JAR 文件而不重建 JAR

c++ - 小随机数生成程序?

c++ - Netbeans 中的标准输入

c++ - 无法访问类 'CObject' 中声明的私有(private)成员?

c++ - 继承C++

c# - 覆盖基类的实现,使得从继承的基类函数调用也调用被覆盖的函数

java - 是否可以隐藏或降低对 Java 中继承方法的访问?

c++ - 从 tr1::regex_search 获取匹配索引

javascript - 原型(prototype)继承和构造函数