让我们考虑以下示例,说明隐式类型转换在哪里 起作用以及在哪里不起作用:
#include <iostream>
#include <vector>
struct Thingy
{
void write()
{
std::cout << "x" << std::endl;
}
};
struct Node
{
Thingy a;
int data;
operator Thingy&(){return a;}
};
void f(Thingy thingy)
{
thingy.write();
}
template <typename TIterator>
void f (TIterator begin, TIterator end)
{
for (TIterator it = begin; it != end; ++it)
it->write();
}
int main()
{
std::vector<Node> vector(10);
f(vector.begin(), vector.end()); // Doesn't compile
f(vector[3]); // compiles
vector[3].write(); // Doesn't compile
return 0;
}
为什么会这样?这
void Node::write();
不应该从根本上不同于:
void write(Node* this);
有什么方法可以让我的示例代码编译并运行?
编辑:
我了解为什么它不起作用的机制,我想了解哲学。为什么 C++ 标准委员会认为这是一个坏主意?