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);  // 字符串既是容器也是单值,这里会作为容器处理  
}
相关推荐
影寂ldy3 分钟前
C# WinForms 窗体继承
开发语言·c#
小白学大数据5 分钟前
无库无捷径,PyTorch 手写完整 Transformer 大语言模型 LLM
开发语言·pytorch·语言模型·transformer
阿pin5 分钟前
Java随笔-JVM内存模型
java·开发语言·jvm·内存模型
虚心的百褶裙37 分钟前
JavaScript性能优化
开发语言·javascript·性能优化
凯瑟琳.奥古斯特43 分钟前
二分查找解力扣1011最优运载能力
开发语言·c++·算法·leetcode·职场和发展
WZF-Sang1 小时前
TCP和UDP协议
linux·服务器·网络·c++·学习·tcp/ip·udp
Tim_101 小时前
【C++】014、左值与右值的区别
开发语言·c++
想人陪的玫瑰1 小时前
winform 能用 Native AOT 吗?——TDS 项目的实战尝试
c++·mfc
天空'之城1 小时前
Linux 系统编程 14:Reactor 反应堆模式
linux·开发语言·网络编程·reactor 反应堆模式
Zhou1411361 小时前
Java常见面试题7
java·开发语言