我有一个我在整个项目/类中继承的小实用程序类(模板化)。
其想法是,它允许轻松地将各种成员打包到类实例中和从类实例中打包出来(对于网络等,并不完全重要)。
我得到的信息如下
template<typename T>
struct Packable
/**
* 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, const T *t)
{
// Call the actual one, but basically do nothing...
return packet << *t;
}
friend sf::Packet& operator <<(sf::Packet& packet, const T &t)
{
// Call the actual one, but basically do nothing...
return packet << &t;
}
friend sf::Packet& operator <<(sf::Packet& packet, T *t)
{
// Call the actual one, but basically do nothing...
return packet << *t;
}
friend sf::Packet& operator <<(sf::Packet& packet, T &t)
{
// Call the actual one, but basically do nothing...
return packet << &t;
}
};简而言之,我要做的就是让它只需要在子类中指定/充实一个方法(用“虚拟”这个词来表示)。
我想要的是提供其他方法,这些方法采用各种形式的类,并根据需要取消对它们的引用,以使用在编译类时将存在的虚方法。
问题是我似乎创建了一些无限循环。
friend sf::Packet& operator <<(sf::Packet& packet, T &t)
{
// Call the actual one, but basically do nothing...
return packet << &t;
}简单地一遍又一遍地调用自己。如何解除引用到它的对象的引用?
发布于 2014-05-27 13:29:26
operator <<有4个重载,它们相互依赖。
<代码>G210
因此,它正在引起无休止的反复。您应该至少将其中一个实现为independent functionality,然后将其余的依赖于此。
您可以这样做,如下所示
template<typename T>
struct Packable
/**
* 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, const T *t)
{
// Call the actual one, but basically do nothing...
return packet << *t;
}
friend sf::Packet& operator <<(sf::Packet& packet, const T &t)
{
// Call the actual one, but basically do nothing...
//return packet << &t;
// Serialize the contents into packet stream
t.serialize(packet);
return packet;
}
friend sf::Packet& operator <<(sf::Packet& packet, T *t)
{
// Call the actual one, but basically do nothing...
return packet << const_cast<const T*>(t);
}
friend sf::Packet& operator <<(sf::Packet& packet, T &t)
{
// Call the actual one, but basically do nothing...
return packet << &t;
}
};这个函数serialize应该在每个T类型的类中实现,否则你会看到编译时错误。
https://stackoverflow.com/questions/23881126
复制相似问题