【问题标题】:Removing CV qualifiers when deducing types using declytype使用 declytype 推断类型时删除 CV 限定符
【发布时间】:2015-08-31 08:51:57
【问题描述】:

我有一个常量声明如下:

const auto val = someFun();

现在我想要另一个具有相同类型“val”但没有常量规范的变量。

decltype(val) nonConstVal = someOtherFun();
// Modify nonConstVal, this is error when using decltype

目前 decltype 保持常量。如何剥离?

【问题讨论】:

  • <type_traits> 包含一个 remove_cv 特征,您可以使用它。
  • 谢谢,正是我想要的!
  • 除了 Jarod42 的回答和 Bo 的评论之外,请注意 auto nonConstVal = someOtherFun() 可能就足够了,并且更具可读性,具体取决于您的代码的其余部分。当然,除非someOtherFun() 返回的东西不完全someFun() 的返回类型。

标签: c++ decltype type-deduction


【解决方案1】:

来自<type_traits>

您可以在 C++14 中使用:

std::remove_cv_t<decltype(val)> nonConstVal = someOtherFun();

或在 C++11 中

std::remove_cv<decltype(val)>::type nonConstVal = someOtherFun();

Demo

【讨论】:

    猜你喜欢
    • 2017-12-27
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 2020-05-04
    • 2015-09-19
    相关资源
    最近更新 更多