zoukankan      html  css  js  c++  java
  • C++11 新特性之 decltypekeyword

    版权声明:本文为博主原创文章,未经博主同意不得转载。 https://blog.csdn.net/lr982330245/article/details/30728131

    decltypekeyword用于查询表达式的类型。与其它特性结合起来之后会有意想不到的效果。

    decltype的语法是

    decltype (expression)

    实例:


    #include <iostream>
    #include <typeinfo>
    using namespace std;
    
    int main()
    {
    	int i;
    	double d;
    	float f;
    	struct A
    	{
    		int i;
    		double d;
    	};
    	
    	decltype(i) i1;
    	cout << typeid(i1).name() << endl; //g++编译器下输出i ,相应int类型
    	decltype(d) d1;
    	cout << typeid(d1).name() << endl;//输出d, double
    	decltype(f) f1;
    	cout << typeid(f1).name() << endl;//输出f,float
    	
    	A *a = new A;
    	decltype(a->i) i2;
    	cout << typeid(i2).name() << endl; //输出i, int
    	decltype(a->d) d2;
    	cout << typeid(d2).name() << endl; //输出d,double 
    	return 0;
    }

    decltype在模板编程中的用处,举个样例,


    template <class T, class U>
    ?

    ?? add(T t, U u) { return t+u; }

    问题在于无法知道t+u返回的实际类型


    解决方法:利用__typeof__扩展编写相当难看的代码


    template <class T, class U>
    __typeof__(*(T*)0 + *(U*)0) add(T t, U u)
    {
    	return t+u;
    }

    而在C++11中。我们能够使用autokeyword与decltype配合

    #include <iostream>
    #include <typeinfo>
    using namespace std;
    
    template <class T, class U>
    auto add(T t, U u) ->decltype(t+u)
    {
    	return t+u;
    }
    
    int main()
    {
    	auto r = add(1, 1.0);
    	cout << typeid(r).name() << endl;
    	
    	return 0;
    }
    





  • 相关阅读:
    11月2号
    2020.9.22 (Java测试)
    2020.8.30 + 每周周报(8)
    2020.8.31
    2020.8.29
    2020.9.23
    伪分布式hbase从0.94.11版本升级stable的1.4.9版本
    python 将列表(也可以是file.readlines())输出多个文件
    hbase0.94.11版本和hbase1.4.9版本的benchamark区别
    idea 配置
  • 原文地址:https://www.cnblogs.com/mqxnongmin/p/10638340.html
Copyright © 2011-2022 走看看