【问题标题】:PreProcessor: store array of strings at compile-timePreProcessor:在编译时存储字符串数组
【发布时间】:2013-03-03 11:34:11
【问题描述】:

我在编译时需要一个字符串容器,它在运行时应该是可迭代的。 但是,我确实需要一个宏,以便生成一些函数(想不出在命名空间级别使用模板化代码的方法)。

但在下面的代码中,我得到了“错误:'class LaLaLa' 中的'sequence' 没有命名类型',这发生在 ASSIGN 宏中(我认为)。 有人可以帮我解决这个问题吗?

#define CREATE_FUNCTION(r, data, i, elem) // creates a function with name 'do_something_with_##elem()'

#define ASSIGN(r, data, i, elem) data::sequence[i] = elem;

#define TO_ARRAY(name, _seq)                                          \
    BOOST_PP_SEQ_FOR_EACH(CREATE_FUNCTION, _, _seq)                   \
    class name                                                        \
    {                                                                 \
    public:                                                           \
        static constexpr std::size_t size = BOOST_PP_SEQ_SIZE(_seq);  \
        static std::string sequence[size];                            \
    };                                                                \
    BOOST_PP_SEQ_FOR_EACH_I(ASSIGN, name, _seq)


TO_ARRAY(LaLaLa, (x)(y)(z)(a))

那我想这样用:

do_something_with_x();
do_something_with_z();
std::vector<std::string> use_strings;
for(size_t i = 0; i < LaLaLa::size; ++i)
{
   use_strings.push_back(LaLaLa::sequence[i]);
}
// use_strings == {"x", "y", "z", "a"}

【问题讨论】:

  • 好吧,你有没有看过你的代码在预处理器完成替换后的样子?
  • 哦,不,没想到 - 我该怎么做?
  • g++ -E file.cpp 如果你使用 gcc。
  • 嗯,我需要包含 ,但 g++ -E -B /path-to/boost-1.48.0/ file.cpp 不能解决这个问题
  • 呃。您的源文件中有必要的#include 语句吗?您不需要 -B ...,如果 boost 在 /usr/include/boost 中,那么 #include&lt;boost/.../...&gt; 会找到文件。

标签: c++ c-preprocessor


【解决方案1】:

问题不在于预处理器——在类定义之后直接使用序列是问题所在。 (需要在函数或类似的东西中完成)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    相关资源
    最近更新 更多