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);  // 字符串既是容器也是单值,这里会作为容器处理  
}
相关推荐
Via_Neo4 分钟前
Bash Game
开发语言·bash
菜菜的顾清寒26 分钟前
C++面试题自用-持续更新
开发语言·c++
t***54432 分钟前
如何在 Dev-C++ 中使用 Clang 调试
开发语言·c++
c++之路34 分钟前
C++ 重载函数、运算符重载、抽象类(接口)
开发语言·c++
xyq202434 分钟前
Ruby 注释
开发语言
格林威35 分钟前
面阵相机 vs 线阵相机:堡盟与海康相机选型差异全解析 附Python实战演示
开发语言·人工智能·python·数码相机·计算机视觉·视觉检测·工业相机
Vect__37 分钟前
快速掌握Python之基础语法和数据结构
开发语言·python
胡利光37 分钟前
Harness Engineering 03|Eval & Trace Harness:验证和追溯的工程组织
android·开发语言·kotlin
汉克老师41 分钟前
GESP2023年6月认证C++三级( 第三部分编程题(1、春游))
c++·数组·计数·gesp三级·gesp3级
aq55356001 小时前
Laravel8.x新特性全解析
c++·elasticsearch·mfc