WTL for MFC Programmers (3)

zhaozj2021-02-08  269

ATL-STYLE TEMPLATES

Even if you can read C Templates without getting a headache

About C template definition, ATL has two things that make people distress. Note the following example:

Class CMYWND: PUBLIC CWINDOWIMPL

{

...

}

That actually is legal, because the C spec says that immediately after the class CMyWnd part, the name CMyWnd is defined and can be used in the inheritance list. The reason for having the class name as a template parameter is so ATL can do the second Tricky Thing, Compile-Time Virtual Function Calls.

The above code is legal because C specifies that as long as the Class CMYWND definition section can use CMYWnd, it is of course used in the definition of the base class table. This is why the class name can be used like a template parameter, which is because of such features, ATL has the second piece of design, compile time virtual function call.

(If you can use CMYWND immediately after the Class CMYWND, can you make a class as your own subclass? It seems that you can do it, because the compiler will find the definition of the base class, if you do yourself Base class, the compiler will prompt the base class without defining - snail hand)

To See this in action, Look at this set of classes:

Note the following definition:

Template

Class B1

{

PUBLIC:

Void Sayhi ()

{

T * pt = static_cast (this); // huh ?? I'll Explain this Below

Pt-> PrintClassName ();

}

protected:

Void PrintClassName () {cout << "this is b1";}

}

Class D1: Public B1

{

// No Overridden Functions At All

}

Class D2: Public B1

{

protected:

Void PrintClassName () {cout << "this is d2";}

}

Main ()

{

D1 D1;

D2 D2;

D1.SAYHI (); // Prints "this is b1"

D2.SAYHI (); // Prints "this is d2"

}

The static_cast (this) is the trick here. It casts this, which is of type B1 *, to either D1 * or D2 * depending on which specialization is being invoked. Because template code is generated at compile-time, (if you wroteclass d3: public B1

you'd be in trouble.) It's safe because the this object can only be of type D1 * or D2 * (as appropriate), and nothing else. Notice that this is almost exactly like normal C polymorphism, except that the SayHi () Method isn't Virtual.

Statement Static_cast (this) is a scam. It converts the THIS of B1 * to D1 * or D2 * through this special call. Because the code of the template is generated at compile, as long as the base class expresses the correct, this conversion guarantee is safe. (If you write this statement: Class D3: Public B1 , then you will encounter trouble). This security is because the THIS object can only be converted to D1 * or D2 * based on the definition, and cannot be converted to other things. This is like the polymorphism of standard C , just the Sayhi () function is not a virtual function.

转载请注明原文地址:https://www.9cbs.com/read-1198.html

New Post(0)