【问题标题】:Why doesn't std::remove_const remove const qualifier?为什么 std::remove_const 不删除 const 限定符?
【发布时间】:2017-09-13 05:48:15
【问题描述】:

请注意,我使用 std::thread 只是为了在错误中获取可读类型:

int main() {
    const int * first;
    using deref = decltype(*first);
    std::thread s = std::remove_const<deref>::type{}; // const int ???
    std::thread s2 = deref{}; // const int
    std::thread s3 = std::remove_const<const int>::type{}; // int 
}

似乎remove_const&lt;deref&gt;::typeconst int,而不是像我预期的那样可变的int

【问题讨论】:

  • 你的标题是remove_reference,但你并没有在你的身体中使用它。
  • tnx,已修复,在原始代码中同时使用了这两种方法,所以我把它混合了 :)
  • 我建议您使用this 来显示类型而不是您的std::thread 方法,因为它显示的是const int &amp; 的实际类型,而您的方法对您来说是谎言并显示const int
  • mutable 是存储类说明符,不是类型的一部分。

标签: c++ c++11 constants typetraits decltype


【解决方案1】:

注意*first 是一个左值表达式,那么decltype(*first) 的结果类型将是const int&amp;,即对const int 的引用。引用本身不是 const(它不能是 const 限定的,没有像 int&amp; const 这样的东西),在其上使用 std::remove_const 将产生相同的类型,即 const int&amp;

decltype specifier:

  1. 如果参数是T 类型的任何其他表达式,并且

b) 如果表达式的值类别是左值,则decltype 产生 T&amp;;

您可以将std::remove_conststd::remove_reference 一起使用:

std::remove_const<std::remove_reference<deref>::type>::type // -> int
                                        ^^^^^               // -> const int &
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        // -> const int

顺便说一句:

请注意,我使用 std::thread 只是为了在错误中获取可读类型:

请注意,对于这种情况,它没有给出正确的类型。这是来自Effective Modern C++ (Scott Meyers) 的类模板帮助器:

template<typename T>
class TD;

并将其用作

TD<deref> td;

您将收到包含deref 类型的错误消息,例如来自clang

prog.cc:16:11: error: implicit instantiation of undefined template 'TD<const int &>'
TD<deref> td;
          ^

【讨论】:

  • Aaa这就是为什么你应该写int const &amp;而不是const int&amp;...那么问题的答案是显而易见的。
猜你喜欢
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 2017-10-31
  • 2018-11-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-16
相关资源
最近更新 更多