我希望能够使用如下所示的 if
语句:
if (input == Positive)
{
// Do something
}
实际做的事情看起来像这样:
if (input == "yes" ||input == "Yes" ||input == "YES" ||input == "Ya" ||input == "ya" (etc all the rest of positive words/ways to say yes))
{
// Do something
}
我在想我会把我的代码保存在一个静态库中(虽然我对它们了解不多,所以如果有更好的方法请随时纠正我)这样我就可以从我使用的任何 future 程序中访问它而且我不必一遍又一遍地复制粘贴相同的代码。有什么办法吗?或者类似的东西?
非常感谢:)
有很多方法可以测试是否包含在内。最自然的是使用集合:
#include <set>
#include <string>
static const std::set<std::string> positive_answers =
{ "yes", "Yes", "YES", "Ya", "ya" };
if (positive_answers.count(input) > 0) {
// Do something
}
这是上面的完整程序版本:
#include <iostream>
#include <set>
#include <string>
int main()
{
std::string input = "YES";
static const std::set<std::string> positive_answers =
{ "yes", "Yes", "YES", "Ya", "ya" };
if (positive_answers.count(input) > 0) {
std::cout << "Agreed\n";
} else {
std::cout << "Disagreed\n";
}
}
您可以考虑使用可变参数模板:
template<typename T, typename... U>
bool is_in(T candidate, U... positives)
{
const std::set<std::string> positive_answers{{positives...}};
return positive_answers.count(candidate) > 0;
}
这样使用:
if (is_in(input, "yes", "Yes", "YES", "Ya", "ya"))
这可行,但如果 input
是 C 风格的字符串 (char*
),请小心,因为这将使用指针的比较函数。