我正在尝试建立一个将比较用户指定数量的变量的宏,如下所示:
#include <iostream>
//compares x to only a and b
#define equalTo(x, a, b) x != a && x != b
int main()
{
int x;
do
{
std::cout << "x = ";
std::cin >> x;
} while (equalTo(x, 1, 2)); //I wanna input as many as i want to be compared to "x"
//for example i want equalTo(x, 1, 2, 3, 4, 5) to work too, without a new macro
std::cout << "x = " << x;
std::cin.ignore();
std::cin.get();
return 0;
}
我有点卡住,不知道该去哪里。
最佳答案
我不会对宏执行此操作,但是可变参数模板提供了一种解决方案:
#include <ctime>
#include <cstdlib>
#include <iostream>
template<typename X, typename Arg>
bool notEqualTo(X x, Arg arg)
{
return x != arg;
}
template<typename X, typename Arg, typename... Args>
bool notEqualTo(X x, Arg arg, Args... args)
{
return notEqualTo(x, arg) && notEqualTo(x, args...);
}
int main()
{
std::srand(std::time(0));
for(int i = 0; i < 10; ++i)
{
int x = std::rand() % 10;
int a = std::rand() % 10;
int b = std::rand() % 10;
int c = std::rand() % 10;
std::cout << x << ": (" << a << ", " << b << ", " << c << ") ";
std::cout << std::boolalpha << notEqualTo(x, a, b, c) << '\n';
}
}
输出:
5: (9, 8, 0) true
7: (4, 3, 4) true
1: (3, 2, 5) true
7: (4, 7, 0) false
8: (9, 9, 8) false
5: (8, 4, 4) true
9: (9, 9, 4) false
8: (8, 6, 3) false
7: (4, 5, 4) true
0: (1, 0, 4) false
关于c++ - 比较未知数量的变量的宏C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31978679/