以下代码是最简单的形式:
struct X {
operator char () const { return 'a'; }
};
int main ()
{
X obj, *p = &obj;
char a = *p; // ok
char c = (true)? *p : 'z';
}
Run Code Online (Sandbox Code Playgroud)
此代码给出了编译器错误,
错误:操作数为?:具有不同类型的'X'和'char'
当类型转换操作符没有歧义时,为什么*p不解决?这样的虚假错误消息是正确的还是g ++错误?charclass X
[ 更新注意:有趣的是这种情况不会产生这样的错误 ]
c++ compiler-errors conditional-operator typecasting-operator
在这里,我想将我的 C++ 代码从版本 2 简化为版本 1。在像 Python 这样的语言中,引用不同类型的变量(如版本 1)很简单。如何在 C++ 中实现类似的代码?
\n#include <iostream>\n#include <vector>\n\n/* version 1: compile failed */\nvoid display(std::vector<int> vi, std::vector<double> vd) {\n // error: operands to ?: have different types\n // \xe2\x80\x98std::vector<double>\xe2\x80\x99 and \xe2\x80\x98std::vector<int>\xe2\x80\x99\n auto& v = vi.empty() ? vd : vi;\n for (const auto &e : v) {\n std::cout << e << " ";\n }\n}\n\n/* version 2 */\nvoid display(std::vector<int> vi, std::vector<double> vd) {\n if (!vi.empty()) {\n for (const auto &e : vi) {\n std::cout << e …Run Code Online (Sandbox Code Playgroud)