相关疑难解决方法(0)

如何删除类似const和非const成员函数之间的代码重复?

假设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)

c++ const class code-duplication c++-faq

228
推荐指数
11
解决办法
3万
查看次数

使用decltype将其强制转换为const

我试图解决一个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?

c++ const decltype c++11

11
推荐指数
1
解决办法
1822
查看次数

标签 统计

c++ ×2

const ×2

c++-faq ×1

c++11 ×1

class ×1

code-duplication ×1

decltype ×1