In C ++, convert the class into a function pointer (implemented using operator overloading, that is, the operator function)

Source: Internet
Author: User

Looking at Objective C ++ over the past few days, STD: tr1: function is mentioned. It is amazing to say that a function pointer can be packaged into a function object, so I want to implement the following myself. Then I think of the implementation method in 2. I can convert a class into a function pointer and implement it through Operator overloading, that is, the operator function. The first method is to use typedef, the second method is to use the template:

Typedef int (* PFT) (char); Class C {public: Operator PFT () {return (PFT) 0 ;}; template <typename T> Class D {public: operator T () {return (t) 0 ;}; int main () {C; int (* PF) (char) = C; D <int (*) (char)> D; int (* pf2) (char) = D; return 0 ;}

I used to think that typedef is just a syntactic sugar to improveCodeReading and reducing the number of character input, but when I try to implement operator without typedef or template, it fails.

I realized that typedef must be used to implement type conversion and analyze the cause. Maybe, during type conversion, you or the compiler must know "what type do you want to convert this class to", that is, you must clearly tell the compiler the target. If typedef is not used, it is equivalent to "the target type is anonymous" and does not conform to the logic! Because neither you nor the compiler knows the target type, even if the compiler knows you, as a user of the code, you do not know, that is, the conversion function cannot be used by the user!

To sum up, you must know the target type, that is, you must use typedef or template!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.