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);  // 字符串既是容器也是单值,这里会作为容器处理  
}
相关推荐
木觞清8 分钟前
喜马拉雅音频链接逆向实战
开发语言·前端·javascript
wuxuanok20 分钟前
苍穹外卖 —— 公共字段填充
java·开发语言·spring boot·spring·mybatis
偷光25 分钟前
浏览器中的隐藏IDE: Console (控制台) 面板
开发语言·前端·ide·php
数字化顾问1 小时前
C++分布式语音识别服务实践——架构设计与关键技术
c++
智能化咨询1 小时前
C++分布式语音识别服务实践——性能优化与实战部署
c++
LL_break1 小时前
线程1——javaEE 附面题
java·开发语言·面试·java-ee
MOON404☾1 小时前
Rust 与 传统语言:现代系统编程的深度对比
开发语言·后端·python·rust
ajassi20001 小时前
开源 C++ QT QML 开发(十四)进程用途
c++·qt·开源
先知后行。1 小时前
Reactor模型和类图设计
java·开发语言
闻缺陷则喜何志丹2 小时前
【C++贪心】P8769 [蓝桥杯 2021 国 C] 巧克力|普及+
c++·算法·蓝桥杯·洛谷