C++11之std::is_same和std::decay

来源:互联网 发布:网络歌手袁晓婕诈骗 编辑:程序博客网 时间:2024/06/07 01:35

使用C++,大家会经常用到模板编程。

模板(Templates)使得我们可以生成通用的函数,这些函数能够接受任意数据类型的参数,可返回任意类型的值,而不需要对所有可能的数据类型进行函数重载。这在一定程度上实现了宏(macro)的作用。

模板在一定程度上使得程序能够更灵活,但也带来了困扰。由于类型的不确定性,导致对不同类型的数据操作存在不确定性。

C++11提供了type_traits头文件,可用来解决与类型相关的问题。

使用时:


#include<type_traits>

C++参考手册对该头文件的解释为:This header defines a series of classes toobtain type information on compile-time.

 

针对数据类型不同,上述同文件提供了两个函数用于判断和辅助判断模板结构,std::is_same判断类型是否一致std::decay退化类型的修饰

下面就分别来介绍其原理和应用举例。

is_same判断类型是否一致

该结构体使用起来相对简单,即判断两个类型是否一样,一样会返回true,不一样则返回false。使用举例如下:

boolisInt = std::is_same<int, int>::value; //为true

当进行模板编程时,可通过此函数对模板参数进行判别,并进行进一步的处理。

当创建一个模板类时,可以通过模板类的方法来做进一步的类型判定,如下:

Tamplate<typename T>
Class test{
Public:
        Boolean Typeidfy(T data)
        {
       If(std::is_same(T, int))
       {…}
       Else
       {…}
        }
}

几点值得注意的是:

1. 

int a = 1;
const int& b = a;

is_same还是能够判断出b为int类型。

2.当模板已指定类型时,is_same会依赖于指定的类型进行判断。

int a = 1;
const int& b = a;
int& c = a;
int d[12];
 
typeCheck<int>(a);        //int type
typeCheck<const int&>(b);//other type
typeCheck<int &>(c);        //other type
typeCheck<const int&>(d[7]);//other type
typeCheck(8);                //int type

std::decay 退化类型的修饰

decay的作用就是把各种引用什么的修饰去掉,如把cosntint&退化为int,这样就能通过std::is_same正确识别出加了引用的类型了

 
#include <iostream>
#include <type_traits>
 
 
template<typename TYPE>
void typeCheck(TYPE data);
 
int _tmain(int argc, _TCHAR* argv[])
{
    int a = 1;
    const int& b = a;
    int& c = a;
    int d[12];
 
    typeCheck<int>(a);//int type
    typeCheck<const int&>(b);//int type
    typeCheck<int &>(c);//int type
    typeCheck<const int&>(d[7]);//int type
    typeCheck(8);//int type
    system("pause");
    return 0;
}
 
template<typename TYPE>
void typeCheck(TYPE data)
{
    if(std::is_same<typename std::decay<TYPE>::type,int>::value)
    {
        std::cout<<"int type"<<std::endl;
    }
    else
    {
        std::cout<<"other type"<<std::endl;
    }
}

 

原创粉丝点击