首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

请问:模板元编程的有关问题

2012-02-21 
请教:模板元编程的问题刚刚学了一点关于模板元编程的知识.写了段代码但怎么都编译不过.各位大大帮忙看看什

请教:模板元编程的问题
刚刚学了一点关于模板元编程的知识.写了段代码但怎么都编译不过.
        各位大大帮忙看看什么问题?
        ///条件判断
        template <bool   Conditon,   class   Then,   class   Else>
        struct   If
        {
                typedef   Then   Result;
        };
               
        template <class   Then,   class   Else>
        struct   If <false,   Then,   Else>
        {
                typedef   Else   Result;
        };


        //模板元:循环
        //循环结束
                template <int   i>
                struct   LoopEnd
                {
                        static   void   Run()
                        {
                                //循环结束
                        }
                };

                ///循环
                template <   template <int> class   LoopBody,   int   start,   int   end   >
                struct   Loop
                {
                        static   void   Run()
                        {
                                LoopBody <start> ::OnceLoop();
                                If <   start   <   end,  
                                        Loop <   LoopBody <start   +   1> ,   start   +   1,   end> ,   LoopEnd <start   +   1>   > ,  
                                        LoopEnd <start>   > ::Result::Run();
                        };
                };


static   int   result   =   0;

template <int   i>
class   LoopBody
{
public:
        static   void   OnceLoop()
        {
                result+=i;
                std::cout   < <   result   < <   "   ";


        }  
};

int   main()
{
        Loop <LoopBody,   0,   5> ::Run();
        return   0;
}


[解决办法]

#include <iostream>
using namespace std;

static int result = 0;

template <bool Conditon, class Then, class Else>
struct If
{
typedef Then Result;
};

template <class Then, class Else>
struct If <false, Then, Else>
{
typedef Else Result;
};


//模板元:循环
//循环结束
template <int i>
struct LoopEnd
{
static void Run()
{
//循环结束
}
};

template <int i>
class LoopBody
{
public:
static void OnceLoop()
{
result+=i;
std::cout < < result < < " ";
}
};
///循环
template < template <int> class LoopBody, int start, int end >
struct Loop
{
static void Run()
{
LoopBody <start> ::OnceLoop();

If < start < end,
Loop < LoopBody, start + 1, end > ,
LoopEnd <start + 1>
> ::Result::Run();
};
};


int main()
{

Loop < LoopBody, 0, 5 > ::Run();
return 0;
}
这样可以使用。

热点排行