条件类型定义 [英] Conditional typedefs

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

问题描述

如果我有一些像这样的代码......

If I have a little peice o' code as such...

template <typename _T>
class Foo
{
public:
    typedef const T& ParamType;
    void DoStuff(ParamType thingy);
};

如果 sizeof(_T) <= sizeof(_T*),这可能不是最优的.

This can be non-optimal if sizeof(_T) <= sizeof(_T*).

因此,我想要一个有条件的typedef.如果_T的大小小于或等于指针的大小,则按值传入即可.否则,通过常量引用传递它.这可能吗?我听说了所有关于模板图灵完备的事情,但这让我很头疼.

Therefore, I want to have a conditional typedef. If the size of _T is less than or equal to that of a pointer, just pass it in by value. Otherwise, pass it by const reference. Is this possible? I hear all this stuff about templates being turing complete but this is hurting my head.

推荐答案

使用部分模板很容易实现专业化.

template< typename _T, bool _ByVal >
struct FooBase {
  typedef const _T& ParamType;
};

template< typename _T >
struct FooBase< _T, true > {
  typedef const _T ParamType;
};

template< typename _T, bool _ByVal = sizeof(_T) <= sizeof(void*) >
class Foo : public FooBase< _T, _ByVal > {
  typedef typename FooBase< _T, _ByVal >::ParamType ParamType;
  void DoStuff(ParamType thingy);
};

EDIT 根据 Jeff 的 sol'n 确实应该比较 sizeof(_T)sizeof(_T&) 但我保留了原来的<= void* 要求.

EDIT As per Jeff's sol'n one should indeed compare sizeof(_T) and sizeof(_T&) but I kept the original <= void* requirement.

这篇关于条件类型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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