gpt4 book ai didi

c++ - C++ 中的命名空间类模板继承

转载 作者:行者123 更新时间:2023-11-28 06:52:14 26 4
gpt4 key购买 nike

在之前的一个问题中,我问了 class template inheritance in 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:

我得出的结论是它一定与 namespace 的使用有关。如果我想保留 namespace ,有什么解决方案?

这是方法定义的摘录。我是否必须取消引用 命名空间? (我认为这甚至没有任何意义哈哈)

/**
* 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;
}
//...

这允许编译器按需生成一个免费的非模板函数。其他替代方案包括与您关心的模板或模板特化成为 friend 。

当然,您可以完全忽略友元,只提供 namespace 级别的模板,因为它们是根据public 函数实现的……


相关:

关于c++ - C++ 中的命名空间类模板继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23729016/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com