#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;
}
静态多态校验接口
最新推荐文章于 2025-11-10 01:09:12 发布
305

被折叠的 条评论
为什么被折叠?



