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);  // 字符串既是容器也是单值,这里会作为容器处理  
}
相关推荐
Pluto_CSND22 分钟前
Java中的静态代理与动态代理(Proxy.newProxyInstance)
java·开发语言
将编程培养成爱好1 小时前
C++ 设计模式《外卖骑手状态系统》
c++·ui·设计模式·状态模式
猿太极1 小时前
设计模式学习(3)-行为型模式
c++·设计模式
惊讶的猫2 小时前
LSTM论文解读
开发语言·python
獨枭3 小时前
C# 本地项目引用失效与恢复全攻略
开发语言·c#·visual studio
随意起个昵称3 小时前
【递归】二进制字符串中的第K位
c++·算法
国服第二切图仔3 小时前
Rust开发之Trait 定义通用行为——实现形状面积计算系统
开发语言·网络·rust
mjhcsp3 小时前
C++ 循环结构:控制程序重复执行的核心机制
开发语言·c++·算法
A阳俊yi3 小时前
Spring Data JPA
java·开发语言