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);  // 字符串既是容器也是单值,这里会作为容器处理  
}
相关推荐
程序员黄同学26 分钟前
JavaScript 中的防抖和节流,它们的区别是什么,以及如何实现?
开发语言·前端·javascript
饼干帅成渣26 分钟前
C++病毒(^_^|)(2)
开发语言·c++
代码中の快捷键30 分钟前
集合家族详情
java·开发语言
zoujiahui_20182 小时前
python视频爬虫
开发语言·爬虫·python
流年诠释一切3 小时前
golang 版 E签宝请求签名鉴权方式
开发语言·ios·golang
c-c-developer4 小时前
C++ Primer 语句作用域
开发语言·c++
Мартин.4 小时前
[Meachines] [Easy] Previse EAR+Php files analysis RCE+TRP00F权限提升+Gzip路径劫持权限提升
开发语言·php
一期一祈^6 小时前
C语言——文件操作
c语言·开发语言
Heris996 小时前
2.11 sqlite3数据库【数据库的相关操作指令、函数】
服务器·c语言·开发语言·网络·数据库·tcp/ip·sqlite
DKZ0016 小时前
使用matlab 对传递函数分析bode图和阶跃函数
开发语言·matlab