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

时间:2017-11-29 10:56:35

标签: c++ templates recursion

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

#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();
    }
}

1 个答案:

答案 0 :(得分:3)

对于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> () >>>>>;