使用类型转换运算符 [英] Using the type conversion operator

查看:111
本文介绍了使用类型转换运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个visual studio 2008 C ++应用程序,我需要从一个函数获取信息,它需要一个可变大小的缓冲区。所以,我有一个类,用 std :: vector 来实现一个转换操作符到我想要的类型。

  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>缓冲_;
};

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;
}

我希望能像这样使用它:

  CMibIpForwardTable table = Get(); 

//错误:'dwNumEntries':不是'CMibIpForwardTable'的成员
DWORD entries = table-> dwNumEntries;是否有一个很好的方法来访问底层类型 MIB_IPFORWARDTABLE

?或者我坚持做这样的事情:

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

感谢您,
PaulH

解决方案

除了转换运算符之外,只需重载 operator->

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


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;

Thanks, PaulH

解决方案

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

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

这篇关于使用类型转换运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆