英文:
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 <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
// If elements from lists match, output '1' 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论