Ответы decltype и круглых скобок неверны?

0

Я читал это: decltype и круглые скобки

Но я не могу понять ответы!

Если тип (a-> x) является const double и почему этот код работает?!

#include <iostream>

struct A { double x; };

int main()
{
    A *a=new A;
    decltype(a->x) x3;
    decltype((a->x)) x4 = x3; // is it really const double& ??
    x4=3;// no error !

    const double& x5=x3;
    x5=5;//error 
}
  • 4
    Вы забыли const в A* a = new A; В приведенном вами примере это const A* a = new A(); ,
  • 1
    Является ли (a->x) = x3 законным? Если да, decltype((a->x)) является double&
Показать ещё 1 комментарий
Теги:
c++11
decltype

1 ответ

4
Лучший ответ

На этот вопрос ответили в комментариях. Однако я хотел бы научить будущих читателей тому, как самому ответить на этот вопрос. Добавление небольшого кода в этот пример может заставить сам компилятор рассказать вам, что такое типы:

#include <type_traits>
#include <typeinfo>
#include <iostream>
#ifndef _MSC_VER
#   include <cxxabi.h>
#endif
#include <memory>
#include <string>
#include <cstdlib>

template <typename T>
std::string
type_name()
{
    typedef typename std::remove_reference<T>::type TR;
    std::unique_ptr<char, void(*)(void*)> 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<TR>::value)
        r += " const";
    if (std::is_volatile<TR>::value)
        r += " volatile";
    if (std::is_lvalue_reference<T>::value)
        r += "&";
    else if (std::is_rvalue_reference<T>::value)
        r += "&&";
    return r;
}

#include <iostream>

struct A { double x; };

int main()
{
    A *a=new A;
    std::cout << "decltype(a->x) has type " <<  type_name<decltype(a->x)>() << '\n';
    std::cout << "decltype((a->x)) has type " <<  type_name<decltype((a->x))>() << '\n';
//     decltype(a->x) x3;
//     decltype((a->x)) x4 = x3; // is it really const double& ??
//     x4=3;// no error !
// 
//     const double& x5=x3;
//     x5=5;//error 
}

который выводит:

decltype(a->x) has type double
decltype((a->x)) has type double&

Ещё вопросы

Сообщество Overcoder
Наверх
Меню