这是一个示例,演示了在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"); // without this push_back, my g++ generated exe fails :-(
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
不幸的是,条件中的变量只能用'='声明语法来声明。
这排除了具有显式构造函数的其他可能有用的类型案例。
例如,下一个使用 an 的示例std::ifstream
不会编译...
if (std::ifstream is ("c:/tmp/input1.txt")) { // won't compile!
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 月编辑:使用 auto 来减轻冗长
{
if (auto is = std::ifstream ("missing.txt")) { // ok now !
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(); // ok compiles
// auto y = x; // does not compile
if (auto nocpy = NoCpy (7, 8)) {
std::cout << "true: " << nocpy << std::endl;
} else {
std::cout << "false: " << nocpy << std::endl;
}
}