Software & Finance





C++ - Class Templates





Refer to my earlier post on function templates by clicking here

Likewise function, we can use templates in classes also. I have written a class MySocket which is derived from a templatized class. MySocket will accept the CHTTPImpl class as a default argument for template class name. I have written another base class called CSecureHTTPImpl, this can also be passed as an argument for template class MySocket. Look at the main function code for the usage.

In Standard Template Library(STL) is effectively used in C++ and it is a very good example for template. It has got both function and class templates. Another example would be Active Template Library(ATL) which is widely used in COM technologies.


Source Code


class CHTTPImpl

{

private:

 

    int m_port;

    std::string m_hostname;

 

public:

 

    CHTTPImpl() : m_port(80) { }

    void SendMessage()

    {

    std::cout << "SendMessage from Http Protocol\n";

    }

 

    void RecvMessage()

    {

    std::cout << "RecvMessage from Http Protocol\n";

    }

};

 

class CSecureHTTPImpl

{

private:

 

    int m_port;

    std::string m_hostname;

 

public:

 

    CSecureHTTPImpl() : m_port(443) { }

 

    void SendMessage()

    {

    std::cout << "SendMessage from Secure Http Protocol\n";

    }

 

    void RecvMessage()

    {

    std::cout << "RecvMessage from Secure Http Protocol\n";

    }

};

 

template<class TSockImpl = CHTTPImpl>

class MySocket : public TSockImpl

{

public:

    void SendMessage() { TSockImpl::SendMessage(); }

    void RecvMessage() { TSockImpl::RecvMessage(); }

};

 

int _tmain(int argc, _TCHAR* argv[])

{

    MySocket<> m;

    m.SendMessage();

    m.RecvMessage();

 

    MySocket<CSecureHttpImpl> sm;

    sm.SendMessage();

    sm.RecvMessage();

    return 0;

}

Output


SendMessage from Http Protocol
RecvMessage from Http Protocol
SendMessage from Secure Http Protocol
RecvMessage from Secure Http Protocol