如何检查对象是否为常量?

use*_*944 5 c++

我的问题是我不知道如何检查对象是否为const.我只能使用C++ 98.如何检查对象是否具有const修饰符?如何正确过载功能?

int main(){
  Vec x;
  const Vec y;

  cout<<"Is x const? ";
  y.IfConst(x);     // cout << "no"
  cout<<"\n";

  cout<<"Is x const? ";
  x.IfConst(x)      // cout << "no"
  cout<<"\n";

  cout<<"Is y const? ";
  x.IfConst(y);     // cout << "yes"
  cout<<"\n";

  cout<<"Is y const? ";
  y.IfConst(y);     // cout << "yes"
  cout<<"\n";
  /**/
}
Run Code Online (Sandbox Code Playgroud)

我需要输出看起来像:是x const吗?不是x const?不是y const?是的是常量吗?是

我用了:

void Vec::IsConst(Vec const &vecc) const{
  std::cout << "YES" << std::endl;      
}

void Vec::IsConst(Vec const &vecc) {
  std::cout << "NO" << std::endl;       
}
Run Code Online (Sandbox Code Playgroud)

qua*_*dev 11

constness是已知的并且仅用作编译时,在运行时信息不存在,它没有任何意义.

但是,在编译时,如果您有一个符合C++ 11的编译器,则可以在std::is_const 类型上使用标准类型特征:

int main() 
{
    std::cout << std::boolalpha;
    std::cout << std::is_const<const int>::value << '\n';
    std::cout << std::is_const<Vec>::value  << '\n';
}
Run Code Online (Sandbox Code Playgroud)

如果您没有c ++ 11编译器,则可以使用boost 1.


use*_*944 2

为了解决我的问题,我需要重载函数

void Vec(Vec const &Vecc) const{
std::cout << "YES" << std::endl;            
}

void Vec(Vec const&Vecc){                        
std::cout << "YES" << std::endl;            
}

void Vec(Vec &Vecc) const {
std::cout << "NO" << std::endl;     
}

void Vec(Vec &Vecc) {
std::cout << "NO" << std::endl;     
}
Run Code Online (Sandbox Code Playgroud)