【问题标题】:What's the equivalent of std::is_const for references to const?对于 const 的引用,std::is_const 的等价物是什么?
【发布时间】:2015-06-12 15:30:09
【问题描述】:

考虑代码:

int const  x = 50;
int const& y = x;
cout << std::is_const<decltype(x)>::value << endl; // 1
cout << std::is_const<decltype(y)>::value << endl; // 0

这是有道理的,因为y 不是const 引用,而是对const 的引用。

是否存在foo 使得std::foo&lt;decltype(y)&gt;::value 为1?如果不是,如何定义我自己的?

【问题讨论】:

  • std::remove_reference 有帮助吗?
  • 你的意思是std::is_const&lt;decltype(x)&gt;::value?而std::is_const&lt;std::remove_reference&lt;decltype(y)&gt;::type&gt;::value 会产生您正在寻找的价值。

标签: c++ types constants


【解决方案1】:

使用remove_reference:

#include <string>
#include <iostream>
#include <type_traits>
using namespace std;

int main()
{
    int const  x = 50;
    int const& y = x;
    cout << std::is_const<std::remove_reference<decltype(x)>::type>::value << endl; // 1
    cout << std::is_const<std::remove_reference<decltype(y)>::type>::value << endl; // 1

    return 0;
}

See on coliru

【讨论】:

  • 为什么要删除对非引用整数的引用?
  • @WhyCry 表明无论底层事物是否是引用它都有效。我假设 OP 正在寻找一个通用的解决方案。
  • cout &lt;&lt; std::is_const&lt;decltype(x)&gt;::value &lt;&lt; endl; // 1 cout &lt;&lt; std::is_const&lt;std::remove_reference&lt;decltype(y)&gt;::type&gt;::value &lt;&lt; endl; 所以这些在不太一般的意义上是基本相同的。 (我的结论)
  • 如文档中所述,如果 T 不是参考,remove_reference 无效。
  • @WhyCry 这里有更简单的事情:cout &lt;&lt; 1 &lt;&lt; endl; cout &lt;&lt; 1 &lt;&lt; endl; :) 如果你有幸先验地知道类型,那么为什么还要为类型特征而烦恼呢?如果您想要一个在类型可能为const 或引用const 时有效的通用解决方案,那么您需要类似于上面的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 2023-03-18
  • 1970-01-01
  • 2016-10-18
相关资源
最近更新 更多