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);  // 字符串既是容器也是单值,这里会作为容器处理  
}
相关推荐
Query*9 小时前
杭州2024.08 Java开发岗面试题分类整理【附面试技巧】
java·开发语言·面试
Onebound_Ed9 小时前
Python爬虫进阶:面向对象设计构建高可维护的1688商品数据采集系统
开发语言·爬虫·python
foxsen_xia9 小时前
Go安装、配置和vsCode配置Go
开发语言·vscode·golang
雍凉明月夜9 小时前
c++ 精学笔记记录Ⅰ
开发语言·c++·笔记
小鹏编程9 小时前
C++ 周期问题 - 计算n天后星期几
开发语言·c++
繁华似锦respect9 小时前
C++ unordered_map 底层实现与详细使用指南
linux·开发语言·c++·网络协议·设计模式·哈希算法·散列表
太阳以西阿9 小时前
【计算机图形学】01 OpenGL+Qt
开发语言·qt
稚辉君.MCA_P8_Java9 小时前
Gemini永久会员 C++返回最长有效子串长度
开发语言·数据结构·c++·后端·算法
Molesidy9 小时前
【C】简易的环形缓冲区代码示例
c语言·开发语言