条件类型定义

编程入门 行业动态 更新时间:2024-10-15 04:26:55
本文介绍了条件类型定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 06:23:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405472.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:定义   条件   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!