当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


C++ is_const用法及代码示例

C++ STL 的 std::is_const 模板用于检查类型是否为 const-qualified。它返回一个显示相同的布尔值。

用法

template  < class T >struct is_const;

模板参数:该模板包含单个参数 T(Trait 类),用于检查 T 是否为 const-qualified 类型。

返回值:此模板返回一个布尔值,如下所示:

  • True:如果类型是 const-qualified。
  • False:如果类型是非常量限定的。

以下示例程序旨在说明 C++ STL 中的 is_const 模板:



程序1:


// C++ program to illustrate
// is_const
  
#include <iostream>
#include <type_traits>
using namespace std;
  
// main program
int main()
{
    cout << boolalpha;
    cout << "is_const:"
         << endl;
    cout << "int:"
         << is_const<int>::value
         << '\n';
    cout << "const int:"
         << is_const<const int>::value
         << '\n';
    cout << "const int&:"
         << is_const<typename remove_reference<const int&>::type>::value
         << '\n';
    return 0;
}
输出:
is_const:
int:false
const int:true
const int&:true

程序2:


// C++ program to illustrate
// is_const
  
#include <iostream>
#include <type_traits>
using namespace std;
  
// main program
int main()
{
    cout << boolalpha;
    cout << "is_const:"
         << endl;
    cout << "const int*:"
         << is_const<const int*>::value
         << '\n';
    cout << "int* const:"
         << is_const<int* const>::value
         << '\n';
    cout << "const int&:"
         << is_const<const int&>::value
         << '\n';
  
    return 0;
}
输出:
is_const:
const int*:false
int* const:true
const int&:false

程序3:


// C++ program to illustrate
// is_const
  
#include <iostream>
#include <type_traits>
using namespace std;
  
// main program
int main()
{
    cout << boolalpha;
    cout << "is_const:"
         << endl;
    cout << "float:"
         << is_const<float>::value
         << '\n';
    cout << "const float:"
         << is_const<const float>::value
         << '\n';
    cout << "char const:"
         << is_const<char const>::value
         << '\n';
    cout << "double:"
         << is_const<double>::value
         << '\n';
  
    return 0;
}
输出:
is_const:
float:false
const float:true
char const:true
double:false



相关用法


注:本文由纯净天空筛选整理自rajasethupathi大神的英文原创作品 is_const Template in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。