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


C++ std::make_signed用法及代码示例


<type_traits>头文件中提供了C++ STL的std::make_signed模板。 C++ STL的std::make_signed模板用于通过保留任何cv-qualifiers来获取与T(Triat类)相对应的带符号类型。可以使用std::is_same::value函数检查给定类型T是否为带符号类型。

头文件:

#include<type_traits>

模板类别:

template< class T >
struct make_signed;

template<class T>
using make_signed_t 
    = typename make_signed<T>::type;

用法:

std::make_signed<T>::type

参数:模板std::make_signed接受单个参数T(Trait类),并将类型T设为有符号类型。



下面是在C++中演示std::make_signed的程序:

程序:

// C++ program to illustrate 
// std::make_signed 
// make_signed 
#include <iostream> 
#include <type_traits> 
using namespace std; 
  
// Declare enum 
enum ENUM1 { a, 
             b, 
             c }; 
  
enum class ENUM2:unsigned char { x, 
                                   y, 
                                   z }; 
  
// Driver Code 
int main() 
{ 
  
    // Declare variable using make_signed 
    // for int, unsigned, const unsigned, 
    // enum1 and enum2 
    typedef make_signed<int>::type A; 
    typedef make_signed<unsigned>::type B; 
    typedef make_signed<const unsigned>::type C; 
    typedef make_signed<ENUM1>::type D; 
    typedef make_signed<ENUM2>::type E; 
  
    cout << boolalpha; 
  
    // Check if the above declared variables 
    // are signed type or not 
    cout << "A is signed type? "
         << is_same<int, A>::value 
         << endl; 
  
    cout << "B is signed type? "
         << is_same<int, B>::value 
         << endl; 
  
    cout << "C is signed type? "
         << is_same<int, C>::value 
         << endl; 
  
    cout << "D is signed type? "
         << is_same<int, D>::value 
         << endl; 
  
    cout << "E is signed type? "
         << is_same<int, E>::value 
         << endl; 
  
    return 0; 
}
输出:
A is signed type? true
B is signed type? true
C is signed type? false
D is signed type? true
E is signed type? false

参考: http://www.cplusplus.com/reference/type_traits/make_signed/




相关用法


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