Understanding Conversion Operators in C
Consider the following code snippet:
template <class Type> class smartref { public: smartref() : data(new Type) { } operator Type&() { return *data; } private: Type* data; }; class person { public: void think() { std::cout << "I am thinking"; } }; int main() { smartref<person> p; p.think(); // Why doesn't the compiler try substituting Type? }
In C , conversion operators play a crucial role in type conversions. So, how do they work?
1. Conversion During Argument Passing:
Conversion operators are considered during argument passing, following copy initialization rules. They convert the source type to any compatible type, regardless of whether the conversion is to a reference or not.
2. Conversion to Reference:
Conversion to a reference is allowed in the conditional operator if the converted type is an lvalue. Additionally, binding a reference directly may also involve conversion to a reference.
3. Conversion to Function Pointers:
User-defined conversions to function pointers or references are used when making function calls.
4. Conversion to Non-Class Types:
Implicit conversions, such as those to boolean, can use user-defined conversion functions.
5. Conversion Function Template:
Templates can be used to create conversion functions that convert a type to any pointer type (except member pointers).
Why Doesn't the Compiler Substitute Type?
In the given example, the compiler doesn't substitute Type because the conversion operator in smartref returns a pointer to the internal data member. When trying to call think(), the compiler infers that p is a pointer to a person object, not a reference to a person object. Therefore, it doesn't make any explicit type substitution.
The above is the detailed content of Why Doesn\'t the Compiler Substitute Type in Conversion Operators?. For more information, please follow other related articles on the PHP Chinese website!