C++20 singular template recursion, static polymorphism, no virtual function overhead

 This way there are no virtual functions, but templates are required everywhere

#include <iostream>
#include "common/log.h"
#include <limits>
#include <vector>
#include <span>
#include <array>
#include <type_traits>
#include <cmath>
#include <memory>
#include <variant>
using namespace AdsonLib;
template<typename T>
struct Animal{
    void bark(){
        static_cast<T&>(*this).bark();
    }
};

struct Dog : public Animal<Dog> {
    void bark(){
        LOG(INFO) << "dog bark: wang wang wang";
    }
};

struct Cat : public Animal<Cat> {
    void bark(){
        LOG(INFO) << "cat bark: miao miao miao";
    }
};
template <typename T>
void play(Animal<T> &animal) {
    animal.bark();
}
int main(int argc, char *argv[]) {
    Dog d;
    Cat c;
    play(d);
    play(c);
}

Guess you like

Origin blog.csdn.net/wyg_031113/article/details/128299356