#include <iostream>
#include <variant>
#include <vector>
#include <string>
using namespace std;
class Car
{
int speed = 1000;
public:
void draw()const {
cout << speed << endl;
}
};
class tiger
{
string name{ "maomao" };
public:
//void draw() {
// cout << name << endl;
//}
void eat() const
{
cout << "fish" << endl;
}
};
class Game
{
public:
void draw()const {
cout << "LOL" << endl;
}
};
int main()
{
Car car;
tiger tig;
Game g;
vector<variant<Car, tiger, Game>> coll{car,tig,g};//异质集合
for (const auto& elem : coll)
{
std::visit([]( auto&obj) {
if constexpr (std::is_convertible_v<decltype(obj), tiger>)
{
obj.eat();
}
else
{
obj.draw();
}
}, elem);
}
return 0;
}
使用std::variant实现多态异质集合
于 2024-05-31 14:34:00 首次发布