这是一个示例,说明在if条件中声明的变量的非典型用法。
变量的类型int &
既可以转换为布尔值,又可以在then和else分支中使用。
#include <string>
#include <map>
#include <vector>
using namespace std;
vector<string> names {"john", "john", "jack", "john", "jack"};
names.push_back("bill");
map<string, int> ages;
int babies = 0;
for (const auto & name : names) {
if (int & age = ages[name]) {
cout << name << " is already " << age++ << " year-old" << endl;
} else {
cout << name << " was just born as baby #" << ++babies << endl;
++age;
}
}
输出是
john was just born as baby #1
john is already 1 year-old
jack was just born as baby #2
john is already 2 year-old
jack is already 1 year-old
bill was just born as baby #3
不幸的是,条件中的变量只能用'='声明语法声明。
这排除了使用显式构造函数的其他可能有用的类型的情况。
例如,下一个使用的示例std::ifstream
将不会编译...
if (std::ifstream is ("c:/tmp/input1.txt")) {
std::cout << "true: " << is.rdbuf();
} else {
is.open("c:/tmp/input2.txt");
std::cout << "false: " << is.rdbuf();
}
编辑于2019年1月...您现在可以效仿我解释的无法完成的事情...
这适用于可移动类,例如C ++ 11中的ifstream,甚至适用于自带复制删除功能的C ++ 17起不可复制的类。
2019年5月编辑:使用自动缓解冗长
{
if (auto is = std::ifstream ("missing.txt")) {
std::cout << "true: " << is.rdbuf();
} else {
is.open("main.cpp");
std::cout << "false: " << is.rdbuf();
}
}
struct NoCpy {
int i;
int j;
NoCpy(int ii = 0, int jj = 0) : i (ii), j (jj) {}
NoCpy(NoCpy&) = delete;
NoCpy(NoCpy&&) = delete;
operator bool() const {return i == j;}
friend std::ostream & operator << (std::ostream & os, const NoCpy & x) {
return os << "(" << x.i << ", " << x.j << ")";
}
};
{
auto x = NoCpy();
if (auto nocpy = NoCpy (7, 8)) {
std::cout << "true: " << nocpy << std::endl;
} else {
std::cout << "false: " << nocpy << std::endl;
}
}