我对 C++ 很陌生,我需要澄清从 Java 移植一个项目。
在Java中,我可以用泛型声明一个基类及其派生类,方法是:
public class GenericHost{
public enum HostType{
server,
client
}
public HostType type_;
}
public class MyClient extends GenericHost{
public String clientName;
}
public class MyServer extends GenericHost{
public String serverName;
}
public abstract class GenericNetwork<hostType extends GenericHost> {
public enum NetworkType{
central,
peripheral
}
private NetworkType type_;
protected hostType masterHost;
public hostType getMasterHost(){
return masterHost;
}
public abstract String getName();
}
public class CentralNetwork extends GenericNetwork<MyServer>{
@Override
public String getName(){
return masterHost.serverName;
}
}
public class PeripheralNetwork extends GenericNetwork<MyClient>{
@Override
public String getName(){
return masterHost.clientName;
}
}
这使我能够:
在派生类中,我可以使用指定派生类的方法和变量(例如
serverName
/clientName
inCentralNetwork
/PeripheralNetwork
),而不仅仅是基类的派生类是倾斜的,因此编译器/编辑器可以在代码编辑期间向我建议每个方法和变量
我被迫使用从基类(
GenericNetwork
/GenericHost
)派生的类,每个错误都在编译时而不是运行时每个使用泛型的方法/变量都将在派生类中被视为子类而不是基类(例如,在 中
CentralNetwork
,getMasterHost
将返回派生类,而MyServer
不是基类GenericHost
)。
我想知道 C++ 中是否存在类似的东西。我已经在寻找模板、继承和子类型,但是我找不到像在 Java 中那样做更聪明的事情的方法。我希望我错过了什么...
编辑:这是我在 C++ 中尝试的:
class GenericHost{
public enum HostType{
server,
client
}
public HostType type_;
}
class MyClient : public GenericHost{
public String clientName;
}
class MyServer : public GenericHost{
public String serverName;
}
template<class hostType : GenericHost> <--WISH, forced base class
class GenericNetwork {
public enum NetworkType{
central,
peripheral
}
private NetworkType type_;
protected hostType masterHost;
public hostType getMasterHost(){
return masterHost; <--WISH, should return MyServer / Myclient in derived class
}
public virtual std::string getName();
}
class CentralNetwork<MyServer> : public GenericNetwork{
public std::string getName(){
return masterHost.serverName; <--WISH, tiped and suggested by editor / compiler
}
}
class PeripheralNetwork<MyClient>: public GenericNetwork{
public std::string getName(){
return masterHost.clientName; <--WISH, tiped and suggested by editor / compiler
}
}
我现在没有 C 项目,所以我在运行中重写了它,抱歉有任何错误......