C++ 11 : Variadic Templates , Example

In Lisp, we can use variadic function parameters like this:

(in Emacs shell)

~ $ (+ 1 2 3)
6
~ $ (+ 3 4.5 1)
8.5
~ $ 
In C++, we don't have such abilities.

C++ 11 introduced variadic templates, which can simulate this in compile time.

code:

#include <iostream>

template <typename T>
auto Add(T n) {
  return n;
}

template <typename T, typename... Args>
auto Add(T n1, Args... args) {
  return n1 + Add(args...);
}

int main() {
  std::cout << Add(3, 1.1, 4, 9, 1) << std::endl;
  return 0;
}

The disadvantage is, we can't use this feature in runtime, e.g., read some numbers, then call Add. The only way is use std::accumulate , but this is not feasible in all circumstance.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值