std::vector<std::any> 作为函数参数 代码举例

#include 
#include 
#include 

void ProcessVector(const std::vector<std::any>& vec)
{
    for (const auto& var : vec)
    {
        if (var.type() == typeid(int))
        {
            int value = std::any_cast<int>(var);
            std::cout << "Value (int): " << value << std::endl;
        }
        else if (var.type() == typeid(double))
        {
            double value = std::any_cast<double>(var);
            std::cout << "Value (double): " << value << std::endl;
        }
        else if (var.type() == typeid(std::string))
        {
            std::string value = std::any_cast<std::string>(var);
            std::cout << "Value (string): " << value << std::endl;
        }
        else
        {
            std::cout << "Unknown value type" << std::endl;
        }
    }
}

int main()
{
    std::vector<std::any> vec;

    vec.push_back(42);
    vec.push_back(3.14);
    vec.push_back(std::string("Hello"));

    ProcessVector(vec);

    return 0;
}

你可能感兴趣的:(c++)