C++ Boost PP 如何在两个序列上进行获取和设置差异?

huangapple go评论103阅读模式
英文:

C++ boost PP get set difference on 2 sequence?

问题

如何通过宏函数在Boost PP序列上获取差集?
例如,我有以下代码:

  1. #define FRUIT (apple)(banana)(pear)(orange)
  2. #define EAT (banana)(orange)
  3. #define REST (apple)(pear)

如何获取Boost PP序列:REST

英文:

How to get set difference on Boost PP seq by macro function?
For example, I have

  1. #define FRUIT (apple)(banana)(pear)(orange)
  2. #define EAT (banana)(orange)
  3. #define REST (apple)(pear)

How Could I get boost pp seq: REST?

答案1

得分: 1

在预处理器中无法直接比较字符串。您需要创建一个包含所有可能比较的字典。借助BOOST_PP_EQUAL,该字典可以将值映射到0到BOOST_PP_LIMIT_MAG之间的范围。

  1. #include <boost/preprocessor.hpp>
  2. #define FRUIT (apple)(banana)(pear)(orange)
  3. #define EAT (banana)(orange)
  4. // Dictionary
  5. #define V_apple 0
  6. #define V_banana 1
  7. #define V_pear 2
  8. #define V_orange 3
  9. #define TO_V(x) V_##x
  10. // 如果来自列表的元素匹配,输出'1',否则输出空。
  11. #define COMPARE(r, data, elem) \
  12. BOOST_PP_IF(BOOST_PP_EQUAL(TO_V(data), TO_V(elem)), 1, )
  13. // 如果任何元素与EAT匹配,输出0,否则输出1。
  14. #define FILTER(s, data, elem) \
  15. BOOST_PP_IS_EMPTY(BOOST_PP_SEQ_FOR_EACH(COMPARE, elem, data))
  16. // 只是过滤。
  17. BOOST_PP_SEQ_FILTER(FILTER, EAT, FRUIT)

请注意,这是原始代码的翻译,只提取了代码部分,没有其他内容。

英文:

It is not possible to compare strings in preprocessor. You have to create a dictionary with all possible comparisons. With the help of BOOST_PP_EQUAL the dictionary can just map the values to the range between 0 to BOOST_PP_LIMIT_MAG.

  1. #include &lt;boost/preprocessor.hpp&gt;
  2. #define FRUIT (apple)(banana)(pear)(orange)
  3. #define EAT (banana)(orange)
  4. // Dictionary
  5. #define V_apple 0
  6. #define V_banana 1
  7. #define V_pear 2
  8. #define V_orange 3
  9. #define TO_V(x) V_##x
  10. // If elements from lists match, output &#39;1&#39; anything, otherwise nothing.
  11. #define COMPARE(r, data, elem) \
  12. BOOST_PP_IF(BOOST_PP_EQUAL(TO_V(data), TO_V(elem)), 1, )
  13. // If any element matches EAT, output 0, otherwise 1.
  14. #define FILTER(s, data, elem) \
  15. BOOST_PP_IS_EMPTY(BOOST_PP_SEQ_FOR_EACH(COMPARE, elem, data))
  16. // Just filter.
  17. BOOST_PP_SEQ_FILTER(FILTER, EAT, FRUIT)

huangapple
  • 本文由 发表于 2023年3月3日 17:46:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75625483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定