14

is c++ Template Metaprogramming a form of functional programming? If it is, do some pitfalls like stackoverflow for non-tail recursion relevant for c++ Template Metaprogramming?

For the factorial template example in this question, I guess it is standard functional programming. Or the similarity is only superficial?

#include <iostream>
using namespace std;

template< int n >
struct factorial { enum { ret = factorial< n - 1 >::ret * n }; };

template<>
struct factorial< 0 > { enum { ret = 1 }; };

int main() {
    cout << "7! = " << factorial< 7 >::ret << endl; // 5040
    return 0;
}
Community
  • 1
  • 1
ahala
  • 4,683
  • 5
  • 27
  • 36
  • 7
    C++ templates are actually an extremely pure functional programming language (no side effects!), with the peculiarity of being evaluated entirely at compile time, unlike most functional languages. And the syntax is not very nice. So it makes sense that the same kind of techniques and algorithms that work with one also map to the other. In fact, there exist projects which "desugar" a subset of Haskell to C++ templates. I don't know very much about the performance characteristics / "operational semantics". – glaebhoerl Jul 12 '12 at 23:45
  • 2
    Maybe you should look at [boost::phoenix](http://www.boost.org/doc/libs/1_50_0/libs/spirit/phoenix/doc/html/index.html). – Jesse Good Jul 12 '12 at 23:46
  • 2
    This is definitely a real question. It's just one that is a little abstruse. – Marcin Jul 13 '12 at 16:17
  • @Marcin : The description of 'not a real question' reads "This question is ambiguous, vague, incomplete, **overly broad**, or rhetorical and cannot be reasonably answered in its current form." -- I'd say that more than applies. – ildjarn Jul 13 '12 at 16:57
  • 1
    @ildjarn How is this question broad? It's very specific. – Marcin Jul 16 '12 at 13:34
  • @Marcin : It is _now_, it wasn't when it was closed. – ildjarn Jul 16 '12 at 18:25

3 Answers3

9

is c++ Template Metaprogramming a form of functional programming?

Yep! Template expansion has no side effects, so it is pure-functional.

If it is, do some pitfalls like stackoverflow for non-tail recursion relevant for c++ Template Metaprogramming?

Absolutely. Factorial isn't a good demonstration of this, since the result will overflow long before your stack does, but long recursions can definitely cause the compiler to error out. Interestingly, however, compilers tend to implement templates in such a way that you get automatic memoization. For instance, a naively written implementation of the Fibonacci series will tend to compile in O(n) time rather than O(2^n).

Sneftel
  • 40,271
  • 12
  • 71
  • 104
7

I think the best answer is that the two concepts are completely different things. However, that does not really help, so here are some key points that I can think of:

  • Both C++ templates and (parametric polymorphism in) functional languages like ML are examples of generic programming and so it makes some sense to mention them together in a single question. In academia, there is even Workshop on Generic Programming that often covers C++ template stuff and ML-style functional programming.

  • However, template metaprogramming gives you a way to write code that gets "evaluated" during the compilation of your C++ code and so you can use it only for quite limited tasks. On the other hand, functional programs normally run, well, at runtime and you can define complex data structures, build abstractions etc. (you can do some things using template metaprogramming, but it will look ugly).

  • Why is the factorial example similar to factorials in functional programming? When you're using template meta-programming, you cannot define "mutable variables" (because you are just defining new types or templates) and so template meta-programming might feel a bit like functional programming style.

  • Code written using template metaprogramming is evaluated at compile-time. This means that it cannot depend on user input! It either compiles or not (the compiler may have some restriction on the depth of recursion and give up after some time). On the other hand, functional programs can take some input and then evaluate (which means they can use all the stack or memory available and then fail).

For functional programmers, I know that some functional languages like Agda can also evaluate things at compile-time, but I think it is better to keep things simple!

arrowd
  • 33,231
  • 8
  • 79
  • 110
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • 19
    They are *not* completely different things. It would be closer to the truth to say they are the same thing: C++ template metaprogramming is functional programming. (Though the reverse, of course, is not true.) – glaebhoerl Jul 12 '12 at 23:53
  • 4
    The keypoints contradict your statement: c++ template metaprogramming and functional programming are not the same, but very close. In fact, you can parse a functional program in (a subset of) Haskell, transform and even execute it during compilation time in C++. E.g. see a library here http://abel.web.elte.hu/mpllibs/metaparse/index.html that can do it. – Zólyomi István Jul 13 '12 at 08:28
  • 2
    You both make some good points, but I would still say they are completely different things at the _high level_. At the low level, they share some techincal aspects (like template metaprogramming uses subsets of functional style), but that's not really useful information if you want to consider the big picture. – Tomas Petricek Jul 15 '12 at 11:27
  • 2
    At base, functional programming is programming consisting entirely of side-effect-less evaluation, which perfectly describes template metaprogramming. Looking for features like user input is beside the point; some functional languages (e.g. the lambda calculus) don't take user input. – Sneftel Mar 10 '17 at 12:43
0

Template metaprogramming is in theory a pure functional oriented language, i.e., functions only depend on their arguments, regardless of any global or local state. However, it appears that we can capture and retrieve a metaprogramming state using friend injections. Therefore, functions can return different result depending of a global/local metaprogramming state.

Mechap
  • 319
  • 3
  • 9
  • Retrieving a meta-programming state, however, was never intended and, from the ISO committee's view, "is arcane and should be made ill-formed", as per [CWG 2118](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2118). – dfrib Aug 30 '21 at 08:59