[英]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.