开发者

Using the type conversion operator

开发者 https://www.devze.com 2023-02-16 19:04 出处:网络
I have a visual studio 2008 C++ application where I need to get information from a function that takes a variably sized buffer. So, I have a class that backs that type with a std::vector and implement

I have a visual studio 2008 C++ application where I need to get information from a function that takes a variably sized buffer. So, I have a class that backs that type with a std::vector and implements a conversion operator to the type I want.

class CMibIpForwardTable
{
public:
    operator MIB_IPFORWARDTABLE* () 
    { 
        return reinterpret_cast< MIB_IPFORWARDTABLE* >( &buffer_.front() ); 
    }

    ULONG size() const
    {
        return buffer_.size();
    }

    void resize( ULONG size )
    {
        buffer_.resize( size );
    }

private:
    std::vector< BYTE > buffer_;
};

CMibIpForwardTable Get( DWORD* error_code = NULL )
{
    CMibIpForwardTable table;
    ULONG size = 0;

    DWORD ec = ::GetIpForwardTable( NULL, &size, FALSE );
    if( ec == ERROR_INSUFFICIENT_BUFFER )
    {
        table.resize( size );
        ec = ::GetIpForwardTable( table, &size, TRUE );
    }

    if( NULL != error_code && ec != 0 ) 
        *error_code = ec;
    return table;
}

I would like to be able to use it like this:

CMibIpForwardTable table = Get();

// error: 'dwNumEntries' : is not a member of 'CMibIpForwardTable'
DWORD entries = table->dwNumEntries;

Is there a good way to get access to the underlying type MIB_IPFORWARDTABLE? Or am I stuck doing something like this:

MIB_IPFORWARDTABLE* t = table;
DWORD entries = t->dwNumEntries;

Th开发者_如何学Goanks, PaulH


Just overload operator-> in addition to the conversion operator.

MIB_IPFORWARDTABLE* operator-> () { ... }
const MIB_IPFORWARDTABLE* operator-> () const { ... }


You can overload operator-> but please think very carefully before you do this. In general, overloading operators in a way that doesn't have complete transparency is going to cause maintenance problems in the future. Have you considered just adding a "get_entries" function to your class?

0

精彩评论

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