2023年9月9日,周六下午
这个还是挺难学的,我学了好几天...
在这里我会举大量的示例程序,这样可以有一个更好的理解,
不定期更新。
目录
推荐文章:
示例程序一:拼接字符串
示例程序二:求整数和
示例程序三:输出一串整数
这里有一些不错的相关文章
Parameter pack(since C++11) - cppreference.com
Variadic function templates in C++ - GeeksforGeeks
Variadic templates in C++ - Eli Bendersky's website
在谷歌搜索“Variadic Template”就可以找到更多这样的文章
#include
#include
using namespace std;
template
string concatenate(Args... args) {
string result;
for (const auto& arg : {args...}) {
result += arg;
}
return result;
}
int main() {
cout << concatenate("Hello", " ", "world", "!") << endl; // 输出:Hello world!
return 0;
}
#include
using namespace std;
template
int sum(Args... args){
int sum=0;
for(const int& arg:{args...})
sum+=arg;
return sum;
}
int main() {
cout <
示例程序一和二是通过遍历的方式,而这个示例程序是通过递归的方式。
使用递归的方式时要注意,递归到最后时函数的参数是空的,
所以要准备额外准备好一个函数来处理这种情况。
#include
using namespace std;
void print()
{
cout << "最后一个元素"<
void print(T first, Args... args)
{
cout << first << endl;
print(args...);
}
int main()
{
print(1, 2, 3,4,5,6,7);
return 0;
}