c++ - 使用 decltype 将其转换为 const

标签 c++ constants c++11 decltype

我正在尝试解决一个问题,其中 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/

相关文章:

c++ - 如何在 Windows Phone 运行时组件中使用 native 类

ruby-on-rails - 带有 Acts_As_Taggable_On 的 Rails 3 中未初始化的标记常量

c++ - std::bind 分配给 std::function

c++ - 当需要特定类型的 vector 时,通过引用传递空指针 vector

c++11 - 这是 std::underlying_type 的错误吗

c++ - 使用 STL 容器设置 upper_bound

c++ - 以类引用作为第一个参数的可变参数

c++ - 使用 typealias 代替定义中类中定义的 typedef

c++ - 将 const 放在函数声明之后是什么意思?

C 加载一个常量