Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can compilers identify recursion issues in Template Meta programming?

In Template Meta Programming if a recursion is wrongly implemented with a resulting infinite loop, can the language compiler detect it? Or will the compiler just encounter an eventual stack overflow and crashe? My bet would be that compiler cannot detect this because doing so would violate the undecideability of the halting problem.

Am I right with the conclusion? Of course I could try this out with a piece of code, but I would like to hear more qualified thinking in this case.

Edit : Thanks guys, I get a general idea that my inference on the computation theory aspect of tmp was not wrong. I also understand that compiler implementations can have arbitrary recursion depth limits(Of course I reiterate that I could have tested this second part, but it was only my side-point).

like image 442
PermanentGuest Avatar asked Nov 28 '25 02:11

PermanentGuest


2 Answers

You can't in general detect such infinite recursion; template metaprogramming is Turing capable, and to such detection would amount to solving the halting problem. As is usual with Turing hard problems, that doesn't mean you can't detect certain cases.

I think the compilers tend to have a minimum number of levels that templates may nest established by the standard, and a maximum number at which point they'll diagnose a nesting-too-deep.

like image 149
Ira Baxter Avatar answered Nov 30 '25 16:11

Ira Baxter


The standard states that implementations can (and effectively will) limit some quantities that among others include:

Annex B

  • Recursively nested template instantiations, including substitution during template argument deduction (14.8.2)

The compiler will most probably bail out once its predefined limit for this quantity is reached, with an appropriate error message.

like image 42
David Rodríguez - dribeas Avatar answered Nov 30 '25 15:11

David Rodríguez - dribeas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!