find out the type of auto

前端 未结 3 1021
无人及你
无人及你 2020-12-06 15:44

I am playing with generic lambda in C++1y and I often confused by don\'t know what is the type of auto variable/parameter. Is any good way to find it out?

3条回答
  •  [愿得一人]
    2020-12-06 16:20

    this is what I have ended up with. combined with @Konrad Rudolph's answer and @Joachim Pileborg's comment

    std::string demangled(std::string const& sym) {
        std::unique_ptr
        name{abi::__cxa_demangle(sym.c_str(), nullptr, nullptr, nullptr), std::free};
        return {name.get()};
    }
    
    template 
    void print_type() {
        bool is_lvalue_reference = std::is_lvalue_reference::value;
        bool is_rvalue_reference = std::is_rvalue_reference::value;
        bool is_const = std::is_const::type>::value;
    
        std::cout << demangled(typeid(T).name());
        if (is_const) {
            std::cout << " const";
        }
        if (is_lvalue_reference) {
            std::cout << " &";
        }
        if (is_rvalue_reference) {
            std::cout << " &&";
        }
        std::cout << std::endl;
    };
    
    int main(int argc, char *argv[])
    {   
        auto f = [](auto && a, auto b) {
            std::cout << std::endl;
            print_type();
            print_type();
        };
    
        const int i = 1;
        f(i, i);
        f(1, 1);
        f(std::make_unique(2), std::make_unique(2));
        auto const ptr = std::make_unique();
        f(ptr, nullptr);
    
    }
    

    and output

    int const &
    int
    
    int &&
    int
    
    std::__1::unique_ptr > &&
    std::__1::unique_ptr >
    
    std::__1::unique_ptr > const &
    std::nullptr_t
    

提交回复
热议问题