问题
I've got a class which I need to implicitly convert to a few things, with intermediate values, e.g.
struct outer {
struct inner {
operator T() { return T(); }
};
operator inner() { return inner(); }
};
If I have this structure, is it always valid to do, e.g.
void f(T t);
outer o;
f(o);
回答1:
§13.3.3.1.2 [over.ics.user] p1
A user-defined conversion sequence consists of an initial standard conversion sequence followed by a user-defined conversion (12.3) followed by a second standard conversion sequence.
Notice the singular and the missing of the word "sequence". Only one user-defined conversion will ever be considered during an implicit conversion sequence.
回答2:
This works:
struct Foo {}; // renamed T in Foo to avoid confusion!
struct outer {
struct inner {
operator Foo() { return Foo(); }
};
operator inner() { return inner(); }
template <typename T>
operator T () {
return operator inner();
}
};
int main() {
void f(Foo t);
outer o;
f(o);
}
But only because f
is not overloaded, so it is not really a solution.
来源:https://stackoverflow.com/questions/8610511/chaining-implicit-conversion-operators