C ++宏带记忆 [英] C++ Macro with Memory

查看:330
本文介绍了C ++宏带记忆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是最初发布的答案 C ++宏记忆?

但不知何故,我不能够得到这个编译。我可能失去了一些东西。 (我有一种感觉,这是一件C ++可以做)

But somehow I am not able to get this compiled. I might be missing something here. (I have a feeling that this is something C++ can do)

的main.cpp

#include <iostream>
using namespace std;

const char * hello = "hello";
const char * world = "world";

#define VAR

#define MEMORIZE world
#include "memorize.h"
#define MEMORIZE hello
#include "memorize.h"

int main() {
    cout << VAR << endl;
    return 0;
}

memorize.h

memorize.h

#undef VAR
#ifndef MEMORIZE
    # error "No Argument to memorize.h"
#endif
#define VAR MEMORIZE
#undef MEMORIZE

这是我得到的编译错误是这样的:

The compile error that I am getting is this:

[100%] Building CXX object CMakeFiles/main.dir/main.cpp.o
error: use of undeclared identifier 'MEMORIZE'
    cout << VAR << endl;
            ^
note: instantiated from:
#define VAR MEMORIZE
            ^
1 error generated.
make[2]: *** [CMakeFiles/main.dir/main.cpp.o] Error 1
make[1]: *** [CMakeFiles/main.dir/all] Error 2
make: *** [all] Error 2

我真的很想得到这个记忆东西preprocessing阶段工作。有人能帮忙吗?我觉得 BOOST_PP_COUNTER 1.49 也使用这种技术,但我无法弄清楚如何。

I really want to get this memory thing to work in preprocessing phase. Can someone help? I think BOOST_PP_COUNTER in 1.49 also uses this technique but i couldn't figure out how.

推荐答案

您只使用一个 VAR 值(最后一个),因为它只能取一个值。如果您想通过 VAR意味着不同的事情根据上下文,你需要有源语句后,均包括。

You are using only a single VAR value (the last one) because it can take only one value. If you want to mean different things by VAR depending on the context, you need to have source statements after each include.

#define xstr(a) str(a)
#define str(a) #a
int main() {
#define MEMORIZE world
#include "memorize.h"
      cout << VAR << endl;
#undef MEMORIZE
#define MEMORIZE hello
#include "memorize.h"
      cout << VAR << endl;
          return 0;
}

memorize.h:

memorize.h:

#undef VAR
#ifndef MEMORIZE
    # error "No Argument to memorize.h"
#endif
#define VAR xstr(MEMORIZE)

这篇关于C ++宏带记忆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆