tgparkk / notepad

1 stars 0 forks source link

std::any #9

Open tgparkk opened 4 months ago

tgparkk commented 4 months ago

벡터안에 std::any 가 있을때 switch case lambda 로 타입추론 불가능?

tgparkk commented 4 months ago

std::typeid 로 가능?

tgparkk commented 4 months ago
#include <iostream>
#include <vector>
#include <any>

class MyClass1 {
public:
    void print() const {
        std::cout << "MyClass1" << std::endl;
    }
};

class MyClass2 {
public:
    void display() const {
        std::cout << "MyClass2" << std::endl;
    }
};

int main() {
    auto createObjectsAndReturn = []() -> std::vector<std::any> {
        std::vector<std::any> anyVector;

        MyClass1 obj1;
        MyClass2 obj2;

        anyVector.push_back(obj1);
        anyVector.push_back(obj2);

        return anyVector;
    };

    auto returnObjectLambda = [](const std::any& item) -> std::any {
        if (item.type() == typeid(MyClass1)) {
            auto obj = std::any_cast<MyClass1>(item);
            obj.print();
            return obj;
        } else if (item.type() == typeid(MyClass2)) {
            auto obj = std::any_cast<MyClass2>(item);
            obj.display();
            return obj;
        }

        return std::any();
    };

    auto anyVector = createObjectsAndReturn();

    for (const auto& item : anyVector) {
        auto obj = returnObjectLambda(item);
        // 여기서 obj를 사용할 수 있습니다.
    }

    return 0;
}