c++ 17 constexpr

未来已来:从SFINAE到concepts

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

// 一个通用的容器打印函数,支持任何带 begin()/end() 的容器  
template<typename Container>  
auto print_container(const Container& c) ->   
    decltype(std::begin(c), std::end(c), void()) {  
    std::cout << "容器内容: ";  
    for (const auto& item : c) {  
        std::cout << item << " ";  
    }  
    std::cout << std::endl;  
}  

// 对于不是容器的类型,提供一个普通的打印函数  
template<typename T>  
void print(const T& value) {  
    std::cout << "单个值: " << value << std::endl;  
}  

// 智能函数:自动选择合适的打印方式  
template<typename T>  
void smart_print(const T& value) {  
    // 尝试作为容器打印,如果失败就作为单个值打印  
    if constexpr (requires { std::begin(value); std::end(value); }) {  
        print_container(value);  
    } else {  
        print(value);  
    }  
}  

int main() {  
    // 容器类型  
    std::vector<int> vec = {1, 2, 3, 4, 5};  
    std::list<double> lst = {1.1, 2.2, 3.3};  
    
    // 单个值  
    int x = 42;  
    std::string str = "hello";  

    // 自动选择合适的打印方式  
    smart_print(vec);  // 使用容器版本  
    smart_print(lst);  // 使用容器版本  
    smart_print(x);    // 使用单值版本  
    smart_print(str);  // 字符串既是容器也是单值,这里会作为容器处理  
}
相关推荐
海码00726 分钟前
【Hot 100】70. 爬楼梯
数据结构·c++·算法·leetcode·动态规划·hot100
walkskyer41 分钟前
使用 Golang `testing/quick` 包进行高效随机测试的实战指南
开发语言·后端·golang
南瓜胖胖1 小时前
【R语言编程绘图-mlbench】
开发语言·机器学习·r语言
凌康ACG1 小时前
易语言使用OCR
c++·yolo·c#·ocr·易语言
Rousson1 小时前
硬件学习笔记--65 MCU的RAM及FLash简介
开发语言·前端·javascript
慧都小妮子1 小时前
跨平台浏览器集成库JxBrowser 支持 Chrome 扩展程序,高效赋能 Java 桌面应用
开发语言·python·api·jxbrowser·chrome 扩展程序
范纹杉想快点毕业1 小时前
C++多重继承详解与实战解析
开发语言·c++
shenyan~1 小时前
关于 smali:2. 从 Java 到 Smali 的映射
java·开发语言
天桥下的卖艺者2 小时前
R语言使用随机过采样(Random Oversampling)平衡数据集
开发语言·r语言