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

c – 带模板的条件返回类型

发布时间:2020-12-16 10:04:58 所属栏目:百科 来源:网络整理
导读:我想在C中使用与模板相关的条件返回类型. C 11,14和17预览版可在我的环境中使用. 我不是编程的新手,但我是C的新手并且对某些功能有点困惑. 我想要实现的是: 如果template为int32_t,则返回类型为int64_t,int16_t将返回int32_t,int8_t将返回int16_t. 实际上我
我想在C中使用与模板相关的条件返回类型.
C 11,14和17预览版可在我的环境中使用.

我不是编程的新手,但我是C的新手并且对某些功能有点困惑.

我想要实现的是:

如果template为int32_t,则返回类型为int64_t,int16_t将返回int32_t,int8_t将返回int16_t.

实际上我正在使用两者的通用模板:

template <class T,class T2>
static T2 Foo(T bar1,T bar2) { //do something }

int64_t x = Foo<uint32_t,uint64_t>(555555,666666);

我想通过只输入参数类型来使这更加实用.

int64_t x = Foo<uint32_t>(555555,666666);
int32_t x = Foo<uint16_t>(12000,13000;
int16_t x = Foo<uint8_t>(88,99);

我尝试用std :: conditional实现它:

template<typename OtherType,typename T = typename std::conditional<(sizeof(Type) <=   
        sizeof(OtherType)),OtherType,Type>::type>

我愿意使用重载和疯狂的想法.

解决方法

在C中这样做的惯用方法是使用特征.
举个例子:

template<typename> struct foo_ret;
template<> struct foo_ret<uint32_t> { using type = uint64_t; };
template<> struct foo_ret<uint16_t> { using type = uint32_t; };
// And so on...

现在甚至不再需要返回类型的模板参数:

template <class T>
static typename foo_ret<T>::type Foo(T bar1,T bar2) {};

您可以按照要求调用它:

int64_t x = Foo<uint32_t>(555555,666666);

或者,如果您愿意,让编译器推导出T.

(编辑:李大同)

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

    推荐文章
      热点阅读