[英]namespaced class template inheritance in C++
在前面的问题中,我问了C ++中类模板继承的问题。
我现在要添加一个额外的级别!
考虑下面的代码。 (假设成员定义正确且正确)
namespace Game
{
namespace Object
{
template<typename T>
class Packable
{
public:
/**
* Packs a <class T> into a Packet (Packet << T)
* Required for chaining packet packing
*************************************************/
virtual sf::Packet& operator <<(sf::Packet& packet) = 0; // Work-horse, must be defined by child-class
friend sf::Packet& operator <<(sf::Packet& packet, T &t);
friend sf::Packet& operator <<(sf::Packet& packet, T *t);
/**
* Unpacks a <class T> from a Packet (Packet >> T)
* Required for chaining packet unpacking
*************************************************/
virtual sf::Packet& operator >>(sf::Packet& packet) = 0; // Work-horse, must be defined by child-class
friend sf::Packet& operator >>(sf::Packet& packet, T &t);
friend sf::Packet& operator >>(sf::Packet& packet, T *t);
/**
* Unpacks a <class T> from a Packet (T <<= Packet)
* Returns the <class T> for convienence
*************************************************/
//friend T& operator <<=(T t, sf::Packet& packet); // Returning reference to cut down on copying (they're already passing us our own copy)
friend T& operator <<=(T &t, sf::Packet& packet);
friend T* operator <<=(T *t, sf::Packet& packet);
};
}
}
这个Ship类继承自Game :: Object :: Packable
class Ship : public Game::Object::Base<Ship>, public Game::Object::Packable<Ship>
{
public:
Ship( void );
//...
// For packing and unpackinng packets
sf::Packet& operator <<(sf::Packet& packet);
sf::Packet& operator >>(sf::Packet& packet);
}
我们剩下的是以下错误。
(null): "Game::Object::operator<<(sf::Packet&, Ship*)", referenced from:
我得出的结论是,它必须与名称空间的使用有关。 如果我想保留名称空间,该如何解决?
这是方法定义的摘录。 我是否必须dereference
命名空间? (我不认为这意味着什么哈哈)
/**
* Packs a <class T> into a Packet (Packet << T)
* Required for chaining packet packing
*************************************************/
template<class T>
sf::Packet& operator <<(sf::Packet& packet, T *t)
{
// Call the actual one, but basically do nothing... this needs to be overrided
return packet << *t;
}
template<class T>
sf::Packet& operator <<(sf::Packet& packet, T &t)
{
// Call the pointer one, but basically do nothing... this needs to be overrided
return packet << &t;
}
// ... other definitions etc.
朋友声明(非模板非成员)与伙伴函数模板不匹配。 我建议您在类定义中提供实现:
template<typename T>
class Packable
friend sf::Packet& operator <<(sf::Packet& packet, T &t) {
return packet << t;
}
//...
这允许编译器根据需要生成免费的非模板函数。 其他替代方法包括与您关心的模板或模板专业化做朋友。
当然,您可以完全忽略友谊,而只需在命名空间级别提供模板即可,因为它们是根据公共功能实现的……
有关:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.