zoukankan      html  css  js  c++  java
  • decltype操作符

    关于decltype操作符的说明:

    1、在C++中,decltype作为操作符,用于查询表达式的数据类型。decltype在C++11标准制定时引入,主要是为泛型编程而设计,以解决泛型编程中,由于有些类型由模板参数决定,而难以(甚至不可能)表示之的问题。泛型编程在整个1990年代越发流行,对实现类型推导机制的需求也应运而生。为此,许多编译器厂商都基于程序语言现有的功能,自行实现了这类操作符,其实现如typeof,以及一些功能有限,但更易移植的实现。2002年间,比雅尼·斯特劳斯特鲁普提议在C++内标准化这类操作符,并将之加入C++;且建议命之为“decltype”,以反映其具有获取表达式的“声明类型”(Declared Type)的功能。

    2、从语义上说,decltype的设计适合于通用库编写者与编程新手。总体上说,对于目标对象或函数,由decltype推导出的类型与源码中的定义可精确匹配。而正如sizeof操作符一样,decltype亦不需对操作数求值。

    例子:

    #include<iostream>
    #include<string>
    using namespace std;
    
    string::size_type FindChar(const string &s, char c, string::size_type &count)
    {
    	auto ret = s.size();  //字符串总长,来控制循环,同时初始化初始化ret
    	count = 0;
    	for (decltype(ret) i = 0; i != s.size(); ++i)  //decltype获取ret的类型
    	{
    		if (s[i] == c)
    		{
    			if (ret == s.size())  //巧妙使用ret == s.size() 去控制字符C第一次出现,以后都不在统计
    				ret = i;
    			++count;   //上边if只是第一次进去一次,之后都不在进 以后遇到C都只加count
    		}
    	}
    	return ret;
    }
    
    void Test()
    {
    	string s1("lilililililililililili");
    	
    	string::size_type Count = 0;;
    	auto index = FindChar(s1,'l',Count);
    	cout << "第一次出现的位置:" << index << endl;
    	cout << "Count = " << Count << endl;
    }
    
    int main()
    {
    	Test();
    	return 0;
    }


  • 相关阅读:
    codeforces 724G
    P4151 [WC2011]最大XOR和路径 线性基
    2018-2019 ACM-ICPC, Asia Seoul Regional Contest K TV Show Game 2-sat
    codeforces 1198E Rectangle Painting 2 最小点覆盖
    codeforces847J Students Initiation 网络流
    codeforces863F Almost Permutation 费用流
    codeforces1213F Unstable String Sort 思维
    codeforces1156D 0-1-Tree 并查集
    codeforces1156D 0-1-Tree 换根dp
    错误集合
  • 原文地址:https://www.cnblogs.com/melons/p/5791871.html
Copyright © 2011-2022 走看看