C 如果SEQ为空,则不要为每个扩展BOOST_PP_SEQ
如果参数列表为空C 如果SEQ为空,则不要为每个扩展BOOST_PP_SEQ,c,boost,c-preprocessor,C,Boost,C Preprocessor,如果参数列表为空 #define key_evaluate(r, key, sig) key |= 1 << sig; #define getKey(...)\ ({\ ComponentKey key = 0;\ BOOST_PP_SEQ_FOR_EACH(key_evaluate, key, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) key;\ }) int main(void) { ge
#define key_evaluate(r, key, sig) key |= 1 << sig;
#define getKey(...)\
({\
ComponentKey key = 0;\
BOOST_PP_SEQ_FOR_EACH(key_evaluate, key, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))
key;\
})
int main(void)
{
getKey();
}
我不知道
我知道
- 宏通常是有问题的
- 大括号组表达式是非标准的
enum SigKeys {
key0 = 1,
key1 = 2,
key2 = 4,
key3 = 8,
key4 = 16,
};
#include <iostream>
int main(void) {
std::cout << "key1, key2: " << (key1 + key2) << " == " << getKey(1, 2) << "\n";
std::cout << "key2, key4: " << (key2 + key4) << " == " << getKey(4, 2) << "\n";
}
重拍,没有宏
假设您的编译器达到了标准,您只需将其编写为:
template <typename... T>
constexpr ComponentKey getKey(T&&... sig) {
return (0 | ... | (1 << sig));
}
#include <iostream>
int main(void) {
std::cout << "key1, key2: " << (key1 + key2) << " == " << getKey(1, 2) << "\n";
std::cout << "key2, key4: " << (key2 + key4) << " == " << getKey(4, 2) << "\n";
}
key1, key2: 6 == 6
key2, key4: 20 == 20
template <typename... T>
constexpr ComponentKey getKey(T&&... sig) {
return (0 | ... | (1 << sig));
}
ComponentKey getKey(std::initializer_list<int> sig) {
return std::accumulate(sig.begin(), sig.end(), 0,
[](int r, int s) { return r | (1 << s); });
}
ComponentKey getKey(std::initializer_list<int> sig) {
ComponentKey r = 0;
for (auto& s : sig)
r |= 1 << s;
return r;
}