c++ 变长模板

本文探讨了C++模板元参数的使用,通过实现模板匹配和元组打印功能,展示了如何灵活运用模板特性和递归技巧来解决实际编程问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

template<typename T>
void f(const T& t)
{
    cout << t << endl;
}

template<typename T, typename... Arg>
void f(const T& t,   const Arg&... arg)
{
    cout << t << endl;
    f(arg...);
    
}


int main()
{
    f(10, 20, 30);

    system("pause");

    return 0;

}



//////////////////

void print_split(std::ostream&)
{

}

template<class T,class... Types>
void print_split(std::ostream& stream, T&& head, Types&&... rest)
{
    stream << head << ' ';
    print(stream, std::forward<Types>(rest)...);
}

template<class... Types>
void print(std::ostream& stream, Types&&...args)
{
    print_split(stream, std::forward<Types>(args)...);
}


int main()
{
    print(std::cout, 42, 'x', "hello", 3.14159, 0, '\n');

    system("pause");
    return 0;

}


////////////////////////////////////////////////////

template<long ...nums> struct Multiply;

template<long first, long ... last>
struct Multiply<first, last...>
{
    static const long val = first * Multiply<last...>::val;
};

template<>
struct Multiply<>
{
    static const long val = 1;
};


int main()
{
    cout<< Multiply<1, 2, 3, 4, 5>::val << std::endl;

    std::tuple<int, double, std::string> m = std::make_tuple(1, 22.2, "good");


    system("pause");

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值