[Dev] Fun with templates

Brent Verner dev@trilug.org
Wed, 13 Feb 2002 13:32:19 -0500


[2002-02-12 16:26] Tanner Lovelace said:
| All these questions about the STL had me thinking about a class
| I took a few years ago about advanced templates and the STL.
| I thought I might share a few things with the list, if anyone
| is interested.
| 
| First, did you know that apparently templates are turing complete!
| I.e. you can actually calculate things using templates.  If you
| don't believe me, save the following program as fibonacci.cpp
| and run this command:

nice.

| g++ -c fibonacci.cpp 2>&1 | grep Output
| 
| // -- Cut here ---
| template <int n, int f> struct Output {};    // creates output
| 
| template <int n> struct fibo {
|     enum { val = fibo<n-1>::val + fibo<n-2>::val };

caluclate a value in the fibo series.

| };
| template<> struct fibo<1> { enum { val = 1}; };
| template<> struct fibo<0> { enum { val = 0}; };

initializes the fibo generation. try with the following.
  template<> struct fibo<1> { enum { val = 2}; };
  template<> struct fibo<0> { enum { val = 1}; };

| template <int i> struct Fibo_print {
|     Fibo_print<i-1> a;

template recursion, causing the the calculation above to 
generate the fibo value in the line below.

|     enum { val = fibo<i>::val };
|     void f() { a.f(); Output<i,val> d = val; }

illegal conversion/assignment generates the error message.

| };
| template<> struct Fibo_print<1> { 
|     enum { val = fibo<1>::val };
|     void f() { Output<1,val> d = val; }
| };

stops the recursion.

| void foo() {
|     Fibo_print<17> a;
|     a.f();
| }
| // -- End program here --

-- 
"Develop your talent, man, and leave the world something. Records are 
really gifts from people. To think that an artist would love you enough
to share his music with anyone is a beautiful thing."  -- Duane Allman