Thread: Templates vs Virtual

  1. #1
    Deprecated Dae's Avatar
    Join Date
    Oct 2004
    Location
    Canada
    Posts
    1,034

    Question Templates vs Virtual

    Overused topic I know, but this is not about performance.

    If I use templates then, in this example, I would be limited to only creating lists of HTTP clients -OR- FTP clients, but not both types in the same list due to being different types. As apposed to virtual, obviously.

    Sorry about the example and pseudo code.

    Code:
    class Protocol
    
    class HTTP : Protocol
    class FTP : Protocol
    
    
    templates:
    
    class Client<typename protocol>
    
    template <typename protocol>
    func CreateClient()
    
    client = CreateClient<HTTP>()
    client = CreateClient<FTP>()
    
    httpList = std::vector<Client<HTTP> >
    ftpList = std::vector<Client<FTP> >
    
    virtual:
    
    class Client
        Protocol* protocol
    
    func CreateClient(Protocol* protocol)
    
    client = CreateClient(new HTTP)
    client = CreateClient(new FTP)
    
    list = std::vector<Client>
    Oh, and my question is if this is correct, and/or there are better options. Thanks.
    Warning: Have doubt in anything I post.

    GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Or even better:

    Code:
    class Client
    {
    ...
    };
    
    class HTTPClient : public Client
    {
    ...
    };
    
    class FTPClient : public Client
    {
    ...
    };
    
    vector<Client*> list;
    list.push_back(new HTTPClient());
    list.push_back(new FTPClient());

  3. #3
    Deprecated Dae's Avatar
    Join Date
    Oct 2004
    Location
    Canada
    Posts
    1,034
    Well, I wanted protocol abstracted from the client. But if that's your suggestion, I assume you prefer a virtual base class. It comes down to the same thing.
    Warning: Have doubt in anything I post.

    GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. templates and listeners
    By okinrus in forum C++ Programming
    Replies: 1
    Last Post: 06-09-2004, 07:43 PM
  3. virtual functions and templates
    By ygfperson in forum C++ Programming
    Replies: 7
    Last Post: 07-22-2003, 01:10 PM
  4. C++ XML Class
    By edwardtisdale in forum C++ Programming
    Replies: 0
    Last Post: 12-10-2001, 11:14 PM
  5. Exporting Object Hierarchies from a DLL
    By andy668 in forum C++ Programming
    Replies: 0
    Last Post: 10-20-2001, 01:26 PM