what is

metaprogramming

Page 1 of 1

3 Replies - 1007 Views - Last Post: 25 December 2001 - 06:11 PM Rate Topic: -----

#1 nighthawk  Icon User is offline

  • D.I.C Lover

Reputation: 0
  • View blog
  • Posts: 1,269
  • Joined: 11-April 01

what is

Posted 21 December 2001 - 08:35 PM

what is metaprogramming?

this question is spawned by something that null and void said in this thread

Is This A Good Question/Topic? 0
  • +

Replies To: what is

#2 Null and Void  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 204
  • Joined: 29-April 01

Re: what is

Posted 22 December 2001 - 04:31 PM

The metaprogamming version of a simple "pow" function:
template <int Num, class T> inline T Pow(T X) {
  return (X * Pow<Num-1>(X));
}
template <class T> float Pow <1,T> (T X) {
  return X;
}
template <class T> float Pow <0,T> (T X) {
  return T(1);
}


It's basically "compiler inlined recursion" (i.e. recursion that doesn't suck ;)). This isn't that great of an example, you may be able to find better ones online. Most compilers don't have good enough template support to pull that off (GCC does, MSVC doesn't, I know that much).

(Edited by Null and Void at 6:32 pm on Dec. 22, 2001)

Was This Post Helpful? 0
  • +
  • -

#3 nighthawk  Icon User is offline

  • D.I.C Lover

Reputation: 0
  • View blog
  • Posts: 1,269
  • Joined: 11-April 01

Re: what is

Posted 22 December 2001 - 04:36 PM

hmmm, interesting, i think.....i think that at this point in time it's over my head...
Was This Post Helpful? 0
  • +
  • -

#4 Null and Void  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 204
  • Joined: 29-April 01

Re: what is

Posted 25 December 2001 - 06:11 PM

I've found a more useful (and more confusing!) example of metaprogramming:
template <int A, int B> struct BubbleSwap {
    static inline void CompSwap(int *Data) {
        if(Data[A] > Data[B]) {
            int Temp = Data[A];
            Data[A] = Data[B];
            Data[B] = Temp;
        }
    }
};
template <int A, int B> struct BubbleLoop {
    enum { Go = (B<=A-2) };

   static inline void Loop(int *Data) {        BubbleSwap<B,B+1>::CompSwap(Data);        BubbleLoop<((Go) ? A : 0), ((Go) ? (B+1) : 0)>::Loop(Data);    } }; template <> struct BubbleLoop <0,0> {    static inline void Loop(int *Data) { } }; template <int Count> struct BubbleSort {    static inline void Sort(int *Data) {        BubbleLoop<Count-1,0>::Loop(Data);        BubbleSort<Count-1>::Sort(Data);    } }; template <> struct BubbleSort <1> {    static inline void Sort(int *Data) { } };


That actually took me a long time to write (I'm only 1/2 knowledgable with metaprogramming in the first place ;)) considering that it is only a bubble sort algorithm.

(Edited by Null and Void at 8:12 pm on Dec. 25, 2001)

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1