C++ 递归可变模板函数码膨胀
我查看了gcc中的转储文件,以了解编译器如何处理递归变量模板函数 使用此测试代码C++ 递归可变模板函数码膨胀,c++,templates,c++11,recursion,variadic-templates,C++,Templates,C++11,Recursion,Variadic Templates,我查看了gcc中的转储文件,以了解编译器如何处理递归变量模板函数 使用此测试代码 #include <cstdio> #include <cstdarg> using namespace std; int sum(int n, ...) { va_list arguments; va_start(arguments, n); int sum = 0; int argument = n; while (argument != 0)
#include <cstdio>
#include <cstdarg>
using namespace std;
int sum(int n, ...)
{
va_list arguments;
va_start(arguments, n);
int sum = 0;
int argument = n;
while (argument != 0)
{
sum += argument;
argument = va_arg(arguments, int);
}
return sum;
}
int sum2(int n)
{
return n;
}
template<typename... Arguments>
int sum2(int n, Arguments... arguments)
{
return n + sum2(arguments...);
}
int main()
{
printf("%i %i\n", sum(1, 2, 3, 4, 0), sum2(1, 2, 3, 4));
}
倾倒
;; Function int sum(int, ...) (_Z3sumiz, funcdef_no=0, decl_uid=2538, cgraph_uid=0)
;; Function int sum2(int) (_Z4sum2i, funcdef_no=1, decl_uid=2547, cgraph_uid=1)
;; Function int sum2(int, Arguments ...) [with Arguments = {int, int, int}] (_Z4sum2IIiiiEEiiDpT_, funcdef_no=4, decl_uid=2557, cgraph_uid=3)
;; Function int sum2(int, Arguments ...) [with Arguments = {int, int}] (_Z4sum2IIiiEEiiDpT_, funcdef_no=5, decl_uid=2564, cgraph_uid=5)
;; Function int sum2(int, Arguments ...) [with Arguments = {int}] (_Z4sum2IIiEEiiDpT_, funcdef_no=6, decl_uid=2574, cgraph_uid=7)
因此,在递归调用期间,编译器为每个参数生成了3个单独的函数
好的,通过完全优化,像这样的原始情况在没有函数调用的情况下得到优化,但是即使在复杂的情况下,我仍然可以依靠编译器来进行优化吗?或者,当事情变得更加复杂时,递归模板函数仍然容易受到代码膨胀的影响吗?请注意,您说过:“……在递归调用期间。”请考虑一下。这些调用不是递归的。实际上,您正在调用不同的函数。它们是从同一模板发出的,这是您正在使用的语言功能的结果。这些功能必须存在于某个地方。如果优化器足够强大,可以消除它们或内联它们,那就这样吧,但这是您正在使用的功能的本质。如果您担心递归实例化导致的代码膨胀,那么请尝试以一种避免这种情况的方式编写代码-当您可以在一个包扩展中执行所需操作时,不要使用递归。因为您使用的是gcc,您可以使用
\uuuuuu属性((始终\u内联))
标记函数。gcc诊断内联此类函数的故障。
;; Function int sum(int, ...) (_Z3sumiz, funcdef_no=0, decl_uid=2538, cgraph_uid=0)
;; Function int sum2(int) (_Z4sum2i, funcdef_no=1, decl_uid=2547, cgraph_uid=1)
;; Function int sum2(int, Arguments ...) [with Arguments = {int, int, int}] (_Z4sum2IIiiiEEiiDpT_, funcdef_no=4, decl_uid=2557, cgraph_uid=3)
;; Function int sum2(int, Arguments ...) [with Arguments = {int, int}] (_Z4sum2IIiiEEiiDpT_, funcdef_no=5, decl_uid=2564, cgraph_uid=5)
;; Function int sum2(int, Arguments ...) [with Arguments = {int}] (_Z4sum2IIiEEiiDpT_, funcdef_no=6, decl_uid=2574, cgraph_uid=7)