Using 'auto' type deduction - how to find out what type the compiler deduced?

前端 未结 11 1104
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 07:54

How can I find out what type the compiler deduced when using the auto keyword?

Example 1: Simpler

auto tickTime = 0.001;

W

11条回答
  •  死守一世寂寞
    2021-01-30 08:48

    Here's a typeid version that uses boost::core::demangle to get the type name at runtime.

    #include 
    #include 
    #include 
    #include 
    using namespace std::literals;
    
    #include 
    
    template
    std::string type_str(){ return boost::core::demangle(typeid(T).name()); }
    
    auto main() -> int{
        auto make_vector = [](auto head, auto ... tail) -> std::vector{
            return {head, tail...};
        };
    
        auto i = 1;
        auto f = 1.f;
        auto d = 1.0;
        auto s = "1.0"s;
        auto v = make_vector(1, 2, 3, 4, 5);
    
        std::cout
        << "typeof(i) = " << type_str() << '\n'
        << "typeof(f) = " << type_str() << '\n'
        << "typeof(d) = " << type_str() << '\n'
        << "typeof(s) = " << type_str() << '\n'
        << "typeof(v) = " << type_str() << '\n'
        << std::endl;
    }
    

    Which prints this on my system:

    typeof(i) = int
    typeof(f) = float
    typeof(d) = double
    typeof(s) = std::__cxx11::basic_string, std::allocator >
    typeof(v) = std::vector >
    

提交回复
热议问题