首先感谢论坛在将用C ++ 0x函数编写的函数转换为C ++ 03时提供的支持。我还有更多的线要转换。在完成任务之前,我有一个主要的编译错误(在VS 2008中)以修复以下代码。
(错误读作“只允许在全局,名称空间或类范围内使用模板声明”)
#include "stdafx.h"
#define EMPTY(x, func)
#define ACTION(x, func) func(x)
#define IFRETURN(x, func) if (!func(x)) { return; }
#define BIN_TREE_TRAVERSAL(NAME, PRE, IN, POST) \
template <typename node_t, typename func_t> \
void NAME (node_t* proot, func_t const& func) \
{ \
if (proot) \
{ \
PRE(proot, func); \
NAME(proot->left (), func); \
IN(proot, func); \
NAME(proot->right(), func); \
POST(proot, func); \
} \
}
BIN_TREE_TRAVERSAL(inorder, EMPTY, ACTION, EMPTY)
BIN_TREE_TRAVERSAL(preorder, ACTION, EMPTY, EMPTY)
BIN_TREE_TRAVERSAL(postorder, EMPTY, EMPTY, ACTION)
#define LEFT left
#define RIGHT right
#define BIN_TREE_FIRST(NAME, CONTAINER, NEXT, ACT, L, R) \
template <typename node_t, typename func_t> \
void NAME (node_t* proot, func_t const& func) \
{ \
CONTAINER<node_t*> tovisit; \
std::vector<node_t*> visited; \
tovisit.push(proot); \
while (!tovisit.empty()) \
{ \
node_t* pnode = tovisit.NEXT(); tovisit.pop(); \
if (std::find(visited.begin(), visited.end(), pnode) \
== visited.end()) \
{ \
visited.push_back(pnode); \
ACT(pnode, func); \
if (pnode->L()) { tovisit.push(pnode->L()); } \
if (pnode->R()) { tovisit.push(pnode->R()); } \
} \
} \
}
BIN_TREE_FIRST(width_first , std::queue, front, ACTION, LEFT, RIGHT)
BIN_TREE_FIRST(width_first_if, std::queue, front, IFRETURN, LEFT, RIGHT)
BIN_TREE_FIRST(depth_first , std::stack, top, ACTION, RIGHT, LEFT)
BIN_TREE_FIRST(depth_first_if, std::stack, top, IFRETURN, RIGHT, LEFT)
#define BASETREEE_TRAVERSAL(NAME) \
template <typename func_t> void NAME (func_t const& f) \
{ bintree::NAME (m_root, [&f] (node_t* x) { f(x->n); } ); } \
template <typename func_t> void NAME (func_t const& f) const \
{ bintree::NAME (m_root, [&f] (node_t const* x) { f(x->n); } ); }
#define BASETREEE_TRAVERSAL_IF(NAME) \
template <typename func_t> void NAME (func_t const& f) \
{ bintree::NAME (m_root, [&f] (node_t* x) { return f(x->n); } ); } \
template <typename func_t> void NAME (func_t const& f) const \
{ bintree::NAME (m_root, [&f] (node_t const* x) { return f(x->n); } ); }
int _tmain(int argc, _TCHAR* argv[])
{
BASETREEE_TRAVERSAL(preorder)
BASETREEE_TRAVERSAL(inorder)
BASETREEE_TRAVERSAL(postorder)
BASETREEE_TRAVERSAL(width_first)
BASETREEE_TRAVERSAL(depth_first)
BASETREEE_TRAVERSAL_IF(width_first_if)
BASETREEE_TRAVERSAL_IF(depth_first_if)
return 0;
}
如何修复错误。
答案 0 :(得分:5)
尝试在main
之外移动宏调用。
但是,在某些时候,您将不得不使用C ++ 03语法将所有lambdas替换为functor对象。
答案 1 :(得分:2)
这是你的问题:
int _tmain(int argc, _TCHAR* argv[])
{
BASETREEE_TRAVERSAL(preorder)
....
您应该在main
之外声明模板函数。
答案 2 :(得分:1)
以下代码不会在VC2008上编译,你需要符合C ++ 0x的编译器 - VC10就是其中之一,GCC 4.5+就是其中之一。
{ bintree::NAME (m_root, [&f] (node_t* x) { f(x->n); } ); }