加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 根据值的大小自动按值或按引用传递类

发布时间:2020-12-16 07:29:53 所属栏目:百科 来源:网络整理
导读:我有这个类,我想在 Windows上传递LPARAM参数.因为它足够小以适应LPARAM内部我想通过值传递它,但是如果它稍后扩展我希望它自动切换到通过引用传递. 我会用类似的东西 typedef boost :: call_traits CMyClass :: param_type CMyClassParam; 它应该是const CMyC
我有这个类,我想在 Windows上传递LPARAM参数.因为它足够小以适应LPARAM内部我想通过值传递它,但是如果它稍后扩展我希望它自动切换到通过引用传递.

我会用类似的东西

typedef boost :: call_traits< CMyClass> :: param_type CMyClassParam;

它应该是const CMyClass或const CMyClass&
取决于sizeof(CMyClass)< = sizeof(LPARAM)
但call_traits只优化小POD,而不是小类.

typedef由Anycorn的建议负责:
typedef boost :: mpl :: if_c<(sizeof(CMyClass)< = sizeof(LPARAM)),CMyClass,CMyClass&> :: type CMyClassParam;

然后,我如何在CMyClassParam和LPARAM之间进行转换
(如果您不知道,LPARAM是int,足够长以存储指针)

CMyClass::operator LPARAM()
{
    // must be either
    return *(LPARAM*)this;
    //or
    return reinterpret_cast<LPARAM>(this);
}
    //so that I may call:

void SomeWinFunc(LPARAM p);

CMyClass vi;
SomeWinFunc(vi);

// and then get it back:
void SomeWinCallback(LPARAM p)
{
    CMyClassParam vi = (?????)p;
    // which should translate into either
    CMyClass ti = *(CMyClass*)(&p); // make a bitwise copy
    // or
    CMyClass& ti = *(CMYClass*)p;
}

解决方法

那样的东西?

typedef typename mpl::if_c<(sizeof(T) <= MAX),T,T&>::type P;
P param = p;

但我认为编译器会自动为您优化这一点

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读