Sivaram
Sivaram

Reputation: 155

Compile time recursive using C++ template functions

Is the following code is compile time recursive? I would like to know how to confirm this i.e any debugger,profiler etc to understand template programs.

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

Upvotes: 3

Views: 527

Answers (1)

ks1322
ks1322

Reputation: 35845

For gcc you can use -fdump-tree-original option:

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

Now you can see how create_thread template is getting instantiated in generated dump:

$ 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> () >>>>>;

Upvotes: 3

Related Questions