Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is c++ Template Metaprogramming a form of functional programming

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;
}
like image 444
ahala Avatar asked Jul 12 '12 23:07

ahala


People also ask

What is Template metaprogramming used for?

Template metaprogramming is a programming technique that uses templates as blueprints for the compiler to generate code and help developers avoid writing repetitive code.

What is a metaprogramming language?

Metaprogramming is a programming technique in which computer programs have the ability to treat other programs as their data. This means that a program can be designed to read, generate, analyze, or transform other programs, and even modify itself while running.

Are macros metaprogramming?

Meta-Programming uses a program as a data type to generate code; Macros and Reflection are techniques of Meta-Programming in some sense.

Are generics metaprogramming?

Generics are used for metaprogramming in Ada. They are useful for abstract algorithms that share common properties with each other.


1 Answers

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).

like image 141
Sneftel Avatar answered Oct 13 '22 08:10

Sneftel