【问题标题】:Get type contained in variant at run time in C++?在 C++ 运行时获取变量中包含的类型?
【发布时间】:2022-11-10 17:18:04
【问题描述】:

在 C++ 中,如何在运行时打印变体中包含的类型?

我的用例:使用pybind11 将值字典从 Python 传递到 C++,我想打印出接收到的类型。

【问题讨论】:

    标签: c++ c++11 c++17 pybind11


    【解决方案1】:

    在 MSVC 2022 和 C++17 下测试。应该在 gcc 和 clang 上工作,但未经测试。

    #include <string>
    #include <variant>
    #include <type_traits>
    
    /**
     * rief Variant type to string.
     * 	param T Variant type.
     * param v Variant.
     * 
    eturn Variant type as a string.
     */
    template<typename T>
    std::string variant_type_string(T v)
    {
        std::string result;
        if constexpr(std::is_constructible_v<T, int>) { // Avoids compile error if variant does not contain this type.
            if (std::holds_alternative<int>(v)) { // Runtime check of type that variant holds.
                result = "int";
            }
        }
        else if constexpr(std::is_constructible_v<T, std::string>) {
            if (std::holds_alternative<std::string>(v)) {
                result = "string";
            }
        }
        else if constexpr(std::is_constructible_v<T, bool>) {
            if (std::holds_alternative<bool>(v)) {
                result = "bool";
            }
        }
        else {
            result = "?";
        }
        return result;
    }
    

    要使用:

    std::variant<int, std::string> v { 42 };
    std::cout << variant_type_string(v);
    // Prints: int
    

    【讨论】:

    • 不是最好的解决方案。您应该std::visit 带有模板 lambda 的变体,并在其中打印类型,这将使​​其更通用。
    猜你喜欢
    • 2011-12-31
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多