C++ 使用递归模板参数包函数是否会为每次迭代创建特定的函数?
假设我使用参数包重新创建C++ 使用递归模板参数包函数是否会为每次迭代创建特定的函数?,c++,variadic-templates,compiler-optimization,variadic-functions,C++,Variadic Templates,Compiler Optimization,Variadic Functions,假设我使用参数包重新创建printf: void printf(const char* string) { std::cout << string; } template <typename T, typename... Params> void printf(const char* string, T first, Params... p) { while (*string != '\0') { if (*string == '
printf
:
void printf(const char* string)
{
std::cout << string;
}
template <typename T, typename... Params>
void printf(const char* string, T first, Params... p)
{
while (*string != '\0')
{
if (*string == '%' && *(string + 1) != '%')
{
std::cout << first;
string += 2;
printf(string, p...);
return;
}
std::cout << *string++;
}
}
编译器会创建两个具有不同签名的不同函数吗
printf(常量字符*,int,参数…)代码>
和printf(常量字符*,双精度,参数…)代码>
如果是这样,一个带有10个参数的函数调用将导致创建10个不同的函数。编译器是否对此进行了优化?我希望此调用会产生以下两个模板实例:
printf(const char*, int, double);
及
是的,如果您将11个参数传递给这个printf()
,编译器将生成模板函数的10个实例。这就是为什么模板在创建代码膨胀方面享有盛誉,这是理所当然的
如果有,就说
printf("Foo %d\n", 10);
printf("Bar %d\n", 20);
我希望这两个模板实例是相同的,并在链接时合并在一起。但这只是一个小小的安慰。只是给OP的一个评论:这为什么令人惊讶?对于带有一种类型(C)的常规(非参数包)模板;如果它与十种不同的混凝土类型一起使用,将产生十种不同的模板实例。
printf(const char*, double);
printf("Foo %d\n", 10);
printf("Bar %d\n", 20);