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

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

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

问题

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

#define FRUIT (apple)(banana)(pear)(orange)
#define EAT (banana)(orange)

#define REST (apple)(pear)

如何获取Boost PP序列:REST

英文:

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

#define FRUIT (apple)(banana)(pear)(orange)
#define EAT (banana)(orange)

#define REST (apple)(pear)

How Could I get boost pp seq: REST?

答案1

得分: 1

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

#include <boost/preprocessor.hpp>

#define FRUIT (apple)(banana)(pear)(orange)
#define EAT (banana)(orange)

// Dictionary
#define V_apple   0
#define V_banana  1
#define V_pear    2
#define V_orange  3
#define TO_V(x)   V_##x

// 如果来自列表的元素匹配,输出'1',否则输出空。
#define COMPARE(r, data, elem)  \
        BOOST_PP_IF(BOOST_PP_EQUAL(TO_V(data), TO_V(elem)), 1, )
// 如果任何元素与EAT匹配,输出0,否则输出1。
#define FILTER(s, data, elem)  \
        BOOST_PP_IS_EMPTY(BOOST_PP_SEQ_FOR_EACH(COMPARE, elem, data))
// 只是过滤。
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.

#include &lt;boost/preprocessor.hpp&gt;

#define FRUIT (apple)(banana)(pear)(orange)
#define EAT (banana)(orange)

// Dictionary
#define V_apple   0
#define V_banana  1
#define V_pear    2
#define V_orange  3
#define TO_V(x)   V_##x

// If elements from lists match, output &#39;1&#39; anything, otherwise nothing.
#define COMPARE(r, data, elem)  \
        BOOST_PP_IF(BOOST_PP_EQUAL(TO_V(data), TO_V(elem)), 1, )
// If any element matches EAT, output 0, otherwise 1.
#define FILTER(s, data, elem)  \
        BOOST_PP_IS_EMPTY(BOOST_PP_SEQ_FOR_EACH(COMPARE, elem, data))
// Just filter.
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:

确定