惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Last Week in AI
Last Week in AI
D
DataBreaches.Net
腾讯CDC
Recent Announcements
Recent Announcements
有赞技术团队
有赞技术团队
A
About on SuperTechFans
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
云风的 BLOG
云风的 BLOG
罗磊的独立博客
月光博客
月光博客
MyScale Blog
MyScale Blog
U
Unit 42
Martin Fowler
Martin Fowler
Stack Overflow Blog
Stack Overflow Blog
T
Tailwind CSS Blog
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
G
Google Developers Blog
博客园 - 【当耐特】
D
Docker
I
InfoQ
雷峰网
雷峰网

博客园 - 于光远

分区理论知识整理 SPI协议及驱动开发框架 I2C协议及驱动开发框架 使用qemu 加载linux-6.18.1内核 linux 内核 策略模式 单例模式 Linux性能分析:从监控到优化的完整工具链 C++模板元编程实现序列化与反序列化 引用 bootchart linux 脚本打印时间 接口编程 不定参数解析,结合tuple 独立于main运行的程序 类模板继承 std::ostream & operator<< Flash HIDL --HelloWorld
泛型编程
于光远 · 2026-01-30 · via 博客园 - 于光远
template<std::same_as<int>...T>
int sum(T...args){
    auto s = (args+...+0);
    return s;
}

template<typename... Ts>
auto make_tuple(Ts ...args)   -> decltype(std::tuple<Ts...> t(args...)) //c11 写法
auto make_tuple(Ts ...args)  //c14 自动推导
{
    std::tuple<Ts...> t(args...);
    return t;
}

template<std::convertible_to<double>... Ts> //可转成double
void f(Ts ...args){
    std::vector<double>t{1.0+(args)*{args}...};
    for(auto v:t){
        cout<<v<<endl;
    }
    cout<<"sizeof...(args)"<<endl;
}
int main(){
    f(1,2.0f,3,4,1);
    return 0;
}


template<typename ...Base>
class Myclass:public Base...{
    public:
        Myclass():Base()...{}
};
int main(){
    Myclass<BaseClass1,BaseClass2>mc;
}

template<typename ...Ts>
void print_fold(Ts...args){
    ((cout<<args<<endl), ...);
}

void print_recursion(const auto &first, const auto & ...rest){
    cout<<first<<endl;
    if constexpr(sizeof...(rest)>0) {
        print_recursion(rest...);
    }
    
}

//使用常量n进行索引
auto f(auto ...args){
    const int n=sizeof...(args);
    cout<<args...[n]<<endl;
}


template<std::size_t I,typename...Args>
auto element_at(const Args &...args){
    static_assert(I<sizeof...(args),"Index out of bounds");
    return std::get<I>(std::forward_as_tuple(args...));
}

//递归方式获取。
template<std::size_t I,typename T, typename...Args>
auto element_at(T arg0, const Args&... args){
    static_assert(I<1+sizeof...(args),"Index out of bounds");
    if constexpr (I==0)
        return arg0;
    else
        return element_at<I-1>(args...);
}
//c++26
template<std::size_t I, typename ... Args>
auto element_at_1(const Args&...args){
    return args...[I];
}


int main(){
    cout<<element_at<3>(1,2.0,'c',"string")<<endl;
    return 0;
}

 https://zhuanlan.zhihu.com/p/688090551