假设class X我想要返回内部成员的访问权限:
class Z
{
// details
};
class X
{
std::vector<Z> vecZ;
public:
Z& Z(size_t index)
{
// massive amounts of code for validating index
Z& ret = vecZ[index];
// even more code for determining that the Z instance
// at index is *exactly* the right sort of Z (a process
// which involves calculating leap years in which
// religious holidays fall on Tuesdays for
// the next thousand years or so)
return ret;
}
const …Run Code Online (Sandbox Code Playgroud) 我试图解决一个decltype会大大简化问题的问题,但是我遇到了一个使用decltypeon *this并添加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;
}
Run Code Online (Sandbox Code Playgroud)
代码在MSVC2010中编译,但执行会递归,直到发生堆栈溢出.
Ideone报告编译器错误
prog.cpp: In member function 'void Foo::bar()':
prog.cpp:7:38: error: 'const' qualifiers cannot be applied to 'Foo&'
Run Code Online (Sandbox Code Playgroud)
如果我换行
static_cast<const decltype(*this)&>(*this).bar();
Run Code Online (Sandbox Code Playgroud)
至
static_cast<const Foo&>(*this).bar();
Run Code Online (Sandbox Code Playgroud)
它按预期工作.
我是否滥用或误解了decltype?