【问题标题】:decltype and parenthesis answers are wrong?decltype 和括号的答案是错误的?
【发布时间】:2014-02-24 07:12:39
【问题描述】:

我读到这个:decltype and parentheses

但我看不懂答案!

如果 (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 
}

【问题讨论】:

  • 您忘记了const 中的const 在您链接的示例中,它是const A* a = new A();
  • (a-&gt;x) = x3 合法吗?如果是,decltype((a-&gt;x))double&amp;
  • @MarkGarcia tnx 我明白了

标签: c++ c++11 decltype const-reference


【解决方案1】:

这个问题在 cmets 中得到了回答。但是,我想教未来的读者如何自己回答这个问题。在这个例子中添加一点代码可以让编译器自己告诉你类型是什么:

#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&

【讨论】:

    猜你喜欢
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多