Is there a reason declval returns add_rvalue_reference instead of add_lvalue_reference

前端 未结 4 1421
无人及你
无人及你 2020-12-13 18:18

changing a type into a reference to a type, allows one to access the members of the type without creating an instance of the type. This seems to be true for bot

4条回答
  •  没有蜡笔的小新
    2020-12-13 18:52

    Yes, the use of add_rvalue_reference gives the client the choice of specifying whether he wants an lvalue or rvalue object of the given type:

    #include 
    #include 
    #include 
    #ifndef _MSC_VER
    #   include 
    #endif
    #include 
    #include 
    #include 
    
    template 
    std::string
    type_name()
    {
        typedef typename std::remove_reference::type TR;
        std::unique_ptr own
               (
    #ifndef _MSC_VER
                    abi::__cxa_demangle(typeid(TR).name(), nullptr,
                                               nullptr, nullptr),
    #else
                    nullptr,
    #endif
                    std::free
               );
        std::string r = own != nullptr ? own.get() : typeid(TR).name();
        if (std::is_const::value)
            r += " const";
        if (std::is_volatile::value)
            r += " volatile";
        if (std::is_lvalue_reference::value)
            r += "&";
        else if (std::is_rvalue_reference::value)
            r += "&&";
        return r;
    }
    
    int
    main()
    {
        std::cout << type_name())>() << '\n';
        std::cout << type_name())>() << '\n';
    }
    

    Which for me outputs:

    int&&
    int&
    

提交回复
热议问题