静态多态校验接口

#include <iostream>
#include <memory>

// 静态多态,接口的绑定是在编译期间执行的,
// 动态多态,运行期间执行的

struct Line{
    void Draw(){
        std::cout<<"draw line"<<std::endl;
    }
};

struct Circle{
    void Draw(){
        std::cout<<"draw circle"<<std::endl;
    }
};

struct Rectangle{
    int Draw(){
        std::cout<<"not draw"<<std::endl;
        return 0;
    }
    void GetArea(){

    }
};

// 编译时,函数模板会为每个T类型进行实例化(可执行文件相对动态多态大),T类型对象与接口进行绑定
// 相对动态多态安全(绑定期间进行检查,比如对象没有这个接口,容器无法插入,动态多态基类可以指向不同子类类型对象)
template<typename T>
void Static_Test(T t){
    t.Draw();
    // t.GetArea(); 若T是Line、Circle类型会编译报错,没有改方法;
}

void Test(){
    Line l;
    Circle c;
    Static_Test(l); // draw line
    Static_Test(c); // draw circle

    Rectangle t;
    Static_Test(t);// 预想是能够调用正常draw函数,没有正常检查出来
}

// 静态多态有时需要对模板参数提供检查接口能力
template<typename T>
concept DrawObj = requires(T t) {
    { t.Draw() }-> std::same_as<void>;
};

template<typename T>
requires DrawObj<T>
void Static_Check_Test(T t) {
    t.Draw();
}

void Test1(){
    Line l;
    Circle c;
    Static_Check_Test(l); // draw line
    Static_Check_Test(c); // draw circle

    Rectangle t;
   // Static_Check_Test(t); // error, Rectangle对应的Draw返回值不符合
}
int main(){
    
    Test();
    Test1();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值