浅谈:C++中cpp 14 ~ cpp 17

cpp 14 ~ cpp 17

对于每次写std::is_integral<T>::valuestd::enable_if<B>::type都比较麻烦。

因此 cpp 14 建议可以通过另一个简单的符号表示该内容。也就是type trait variable templates的概念。

直到 cpp 17 才在正式标准中进行了全面的完善。

复制代码
// cpp14
template< bool B, class T = void >
using enable_if_t = typename enable_if<B,T>::type;
// cpp17
template< class T >

因此我们可以得到以下的简洁版本。

复制代码
#include <iostream>
#include <type_traits>
#include <vector>

namespace my {
    
template <typename Type>
class vector {
public:
    vector(size_t len, Type val) {
        std::cout << "vector(size_t len, Type val)" << std::endl;
    }

    /**

cpp 20

c++ 是一门不断发展的现代语言,在 cpp 20 中提出了概念和约束到标准中。

requires 是一个关键字。可以直接在模板函数中进行使用。

requires是在template和函数体之间编写,提升可代码可阅读性。

注意一点,requires 子句需要是一个初等表达式 或者 带括号的表达式。

复制代码
#include <concepts>
#include <iostream>
#include <type_traits>
#include <vector>

namespace my {

template <typename Type>
class vector {
public:
    vector(size_t len, Type val) {
        std::cout << "vector(size_t len, Type val)" << std::endl;
    }

    // 使用 requires 关键字
    // 直接写出约束条件
    template <typename Iter>
    requires (!std::is_integral_v<Iter>)
    vector(Iter begin, Iter end) {
        std::cout << "vector(Iter begin, Iter end)" << std::endl;
    }
};
    
}  // namespace my
相关推荐
科技道人7 小时前
记录 默认置灰/禁用 app ‘Search Engine Selector‘ 的disable按钮
开发语言·前端·javascript
伊玛目的门徒7 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
Jerry8 小时前
LeetCode 226. 翻转二叉树
算法
想做小南娘,发现自己是女生喵9 小时前
【无标题】
数据结构·算法
逝水无殇9 小时前
C# 异常处理详解
开发语言·后端·c#
Kx_Triumphs11 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎11 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
玖玥拾11 小时前
C# 语言进阶(十五)C# 游戏服务端 MySQL 数据库
服务器·开发语言·网络·数据库·mysql·c#
铅笔侠_小龙虾11 小时前
Rust 学习目录
开发语言·学习·rust