在水木看到的: "? :" 在何种状况下不能修改为"if (..) {..} else {..}"?
原题是
Can you think of scenarios where replacing "? : "
expressions with a call to "if (..) {..} lese {..}"
would change the semanics of the problem?
[解决办法]
#include <iostream>using namespace std;void f(double){ cout << "double" << endl;}void f(int){ cout << "int" << endl;}int main(){ f(true ? 1 : 1.0); if(true) { f(1); } else { f(1.0); }}
[解决办法]
其实没那么麻烦:
cout << sizeof(true?char(0):int(0)) << endl;
[解决办法]
这有什么不理解的。
iambic给的例子当中,当以“f(true ? 1 : 1.0);”的形式调用式,f的实参是表达式“true ? 1 : 1.0”,C/C++语言中,一个表达式不可能同时有两种类型,所有,f的调用必将绑定到一个确定的重载上去。而第二种情况中,if和else分支中的两次调用,按照C++语言的重载解析规则,显然是不一样的,是实实在在的两种情况。
[解决办法]
f(true ? 1 : 1.0);
因为需要在编译的时候决定使用哪个版本的函数f (int 还是 double)
true ? 1 : 1.0 隐含一个返回类型,而这个类型按类型提升规则得到,所以是double
你可以这样看
cout<<typeid(true ? 1 : 1.0).name()<<endl;
所以选择函数f(double)