开发者

struct forward declaration fails compile

开发者 https://www.devze.com 2023-02-11 04:47 出处:网络
I have the following code, but the compiler says sender_wrapper is undefined, even though I forward declared it. Can I not do a forward declare of a struct? (compiled with VS2003)

I have the following code, but the compiler says sender_wrapper is undefined, even though I forward declared it. Can I not do a forward declare of a struct? (compiled with VS2003)

struct send_wrapper;

struct IPSend
{
    IPSend::IPSend(const send_wrapper& sender) : _sender(sender) {}

    void IPSend::operator()(const std::string& msg)
    {           
        if (!msg.empty())
            _sender.send(msg);
    }

    send_wrapper _sender; //error C2079: 'IPSend::_sender' uses undefined struct 'send_wrapper'

};

struct s开发者_如何学Goend_wrapper 
{
std::auto_ptr<tcp_server> server;

};


Forward declarations of types can only be used to resolve declarations involving pointers and references to that type.

Before the type has been fully defined, the compiler does not know anything about the type; e.g. what members it has, or how big it is. Therefore, you cannot use it as a by-value member of your struct, because the compiler wouldn't know how big to make it, or whether its constructors and destructor are public. On the other hand, you are free to do something like send_wrapper *_p_sender;, because pointers to structs are always the same size. But you still wouldn't be able to access its member functions, etc.


Can I not do a forward declare of a struct?

Yes, but only for references and pointers to such a struct. Once you start poking inside it, such as accessing a member of it, you need the full declaration of the struct — otherwise, how's the compiler going to know your sender has a send() function?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号