使用C 模板函数编译时间递归

Compile time recursive using C++ template functions

本文关键字:编译 时间 递归 函数 使用      更新时间:2023-10-16

以下代码是编译时间递归吗?我想知道如何确认这一点,即任何调试器,探索器等以了解模板程序。

#include <iostream>
#include <vector>
#include <thread>
std::vector<std::thread> vecc;
void thread_fn(){
    std::cout<<"Thread function"<<"n"; 
}
template <int n>
void create_thread(){
    create_thread<n-1>();
    vecc.push_back(std::thread(thread_fn));
}
template<>
void create_thread<0>(){
    vecc.push_back(std::thread(thread_fn));
}
int main()
{
    create_thread<10>();
    for(auto &a: vecc){
        a.join();
    }
}

对于GCC,您可以使用-fdump-tree-original选项:

g++ -fdump-tree-original -Wall -pthread 111.cpp

现在您可以看到create_thread模板在生成的转储中如何实例化:

$ grep create_thread 111.cpp.003t.original
;; Function void create_thread() [with int n = 0] (null)
  create_thread<10> () >>>>>;
;; Function void create_thread() [with int n = 10] (null)
  create_thread<9> () >>>>>;
;; Function void create_thread() [with int n = 9] (null)
  create_thread<8> () >>>>>;
;; Function void create_thread() [with int n = 8] (null)
  create_thread<7> () >>>>>;
;; Function void create_thread() [with int n = 7] (null)
  create_thread<6> () >>>>>;
;; Function void create_thread() [with int n = 6] (null)
  create_thread<5> () >>>>>;
;; Function void create_thread() [with int n = 5] (null)
  create_thread<4> () >>>>>;
;; Function void create_thread() [with int n = 4] (null)
  create_thread<3> () >>>>>;
;; Function void create_thread() [with int n = 3] (null)
  create_thread<2> () >>>>>;
;; Function void create_thread() [with int n = 2] (null)
  create_thread<1> () >>>>>;
;; Function void create_thread() [with int n = 1] (null)
  create_thread<0> () >>>>>;