我正在尝试解决一个问题,其中 decltype
会大大简化事情,但我在 *this< 上使用
并添加一个 decltype
遇到了问题const
限定符。下面的示例代码演示了这个问题。
#include <iostream>
struct Foo
{
void bar()
{
static_cast<const decltype(*this)&>(*this).bar();
}
void bar() const
{
std::cout << "bar" << std::endl;
}
};
int main(int argc, char* argv[])
{
Foo f;
f.bar(); // calls non-const method
return 0;
}
代码在 MSVC2010 中编译,但执行递归直到发生堆栈溢出。
Ideone报告编译器错误
prog.cpp: In member function 'void Foo::bar()':
prog.cpp:7:38: error: 'const' qualifiers cannot be applied to 'Foo&'
如果我换行
static_cast<const decltype(*this)&>(*this).bar();
到
static_cast<const Foo&>(*this).bar();
它按预期工作。
我是否误用或误解了 decltype?
最佳答案
由于表达式 *this
不是 id-expression(即它没有命名实体,如变量),则 decltype(*this)
给出表达式的类型 *this
.该类型是 Foo&
, 所以添加一个 const
限定符并引用它不会改变任何东西:要么它默默地折叠到 Foo&
(遵循引用折叠等规则),或者它是一个错误(const 引用类型)。我不确定哪种行为是正确的,实际上您发现了两个行为不同的编译器。无论如何都没有关系,因为这不是您想要的。
您可以使用 std::remove_reference<decltype(*this)>::type const&
相反,但看起来有点难看。
如果你仍然感到困惑:
int* p;
// decltype(p) is the type of the variable p (or, the declared type)
// int*
// decltype( (p) ) is the type of the expression p
// int*& because p is an lvalue
// decltype(*p) is the type of the expression *p
// int& because *p is an lvalue
关于c++ - 使用 decltype 将其转换为 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7416251/