简体   繁体   English

C ++模板和继承

[英]C++ Templates and Inheritance

Let's say I have a simple Server with a template which accepts a Client as it's template argument: 假设我有一个带有模板的简单服务器,该模板接受客户端作为模板参数:

template<class T>
class Server<T>{
    Server(int port);
}

and a Client is defined something like this: 客户端定义如下:

class Client{
    Client(Server<Client> *server, // <--
           int socket);
};

But I also want say, have the class User inherit from Client ( class User : public Client ), so I could do Server<User> instead of Server<Client> . 但是我也想说,让类UserClient继承( class User : public Client ),所以我可以做Server<User>而不是Server<Client> class User obviously needs to pass Server<Client> as a parameter when constructing Client . User在构造Client时显然需要将Server<Client>作为参数传递。 However, with the current implementation this seems impossible. 但是,对于当前的实现,这似乎是不可能的。

How should I approach this problem? 我应该如何解决这个问题?

What about this? 那这个呢?

template<class T>
class Server<T>{
    Server(int port);
};

template<class Derived>
class Client {
    Client(Server<Derived> *server, int socket);
    virtual ~Client() {} // Base classes should have this
};

class User : public Client<User> {
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM