为什么decltype(*this)不能返回正确的类型?
Why does decltype(*this) not return the correct type?
下面的代码是用vc++十一月2012 CTP编译的。但是编译器给出了一个警告。
我只是想知道这是否是vc++十一月2012 CTP的一个bug。
struct A
{
int n;
A(int n)
: n(n)
{}
int Get() const
{
return n;
}
int Get()
{
//
// If using "static_cast<const A&>(*this).Get();" instead, then OK.
//
return static_cast<const decltype(*this)&>(*this).Get(); // Warning!
}
};
int main()
{
A a(8);
//
// warning C4717: 'A::Get' : recursive on all control paths,
// function will cause runtime stack overflow
//
a.Get();
}
decltype
应用于一个非id表达式,给你一个引用,所以decltype(*this)
已经是A&
了,你不能再把它变成const
了。如果你真的想使用decltype
,你可以这样做:
static_cast<std::decay<decltype(*this)>::type const &>(*this)
或者
static_cast<std::add_lvalue_reference<
std::add_const<
std::decay<decltype(*this)>::type
>::type
>::type
>(*this)
当然,直接写static_cast<A const &>(*this)
要简单得多。
相关文章:
- 如何在模板参数中分离函数类型返回类型和参数
- 为什么要为指针返回类型返回一系列字符?
- 有没有办法根据运行时值的类型返回 constexpr 对象
- 从弱指针返回类型返回共享指针
- 无法为unique_ptr返回类型返回 nullptr
- 为什么双重类型返回无穷大
- std::is_arithmetic 为通用 lambda 中的 int 类型返回 false:未定义的行为?
- C 策略设计具有可变类型返回值
- 根据类型返回一个值
- 在C++中,将double转换为long的类型返回了不正确的值
- 作为宏参数的安装类型返回错误:字符串常量之前的预期非限定 id
- 具有引用类型返回的函数
- C++ 如何使模板<T>f() 为整数 T 返回 -1,为指针类型返回 nullptr
- C++模板:按类型返回值
- 以Integer返回类型返回浮点值
- 使用 C++14 的自动功能类型返回扣除代替 std::common_type 是否始终安全?
- 为什么允许新运算符向每个指针类型返回*void
- 适当的函数返回类型返回日期时间
- c++中布尔类型返回函数的默认返回值
- 在c#中使用非托管c++代码对所有double类型返回0