c++ - 如何写is_reference_const函数,使is_reference_const<const int&>::value`为true

标签 c++

我们看到std::is_const<const int&>::value总是假的。所以这条指令 #1 永远不会执行。

template <typename T>  void g(T&& val)
    {
      if(is_const<T>::value)
      {
      #1  if(is_lvalue_reference<T>::value)cout<<"const l reference"<<endl;
          else if(is_rvalue_reference<T>::value)cout<<"const r reference"<<endl;
          else cout<<"const int"<<endl;
      }else
      {
          if(is_lvalue_reference<T>::value)cout<<"l reference"<<endl;
          else if(is_rvalue_reference<T>::value)cout<<" r reference"<<endl;
          else cout<<" int"<<endl;
      }

    }

为什么STL没有为这个问题提供is_reference_const函数?我们可以为此编写这个函数吗? 最后,这个函数如is_reference_const<const int&>::value是真的。

最佳答案

任何东西都在标准中,因为有人想要它,并投入精力让它达到标准,并说服委员会这是一个好主意。

这个有效:

#include <type_traits>
#include <iostream>

template <typename T>
struct is_reference_const
{
        static const bool value = std::is_reference<T>::value && std::is_const<typename std::remove_reference<T>::type>::value;
};

int main()
{
        std::cout << is_reference_const<const int &>::value << std::endl;
        std::cout << is_reference_const<const int>::value << std::endl;
        std::cout << is_reference_const<int &>::value << std::endl;
        std::cout << is_reference_const<int>::value << std::endl;
}

1
0
0
0

我很惊讶is_const<const int&>::valuefalse .

关于c++ - 如何写is_reference_const函数,使is_reference_const<const int&>::value`为true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27053433/

相关文章:

C++:C 结构的继承或类成员?

c++ - 打开给定文件夹中的所有文本文件

c++ - fftw 和在线 DFT 计算器得到不同的结果

c++ - 无论代码如何,VS 构建成功

c++ - 编译器标志 -l 的位置

c++ - 程序终止时访问冲突 C++

c++ - 错误 : invalid conversion from ‘const char*’ to ‘int’ [-fpermissive]

c++ - 双字符串转换和语言环境

c++ - 读取 filebuf 的等价物?

c++ - XML - SelectNodes - 如何获取具有某些值的属性的节点 (MFC)