读书人

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

发布时间: 2012-02-21 16:26:23 作者: rapoo

请教:模板元编程的问题
刚刚学了一点关于模板元编程的知识.写了段代码但怎么都编译不过.
各位大大帮忙看看什么问题?
///条件判断
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;
}
这样可以使用。

读书人网 >C++

热点推荐