按返回类型重载模板 [英] Overloading template by Return Type

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

问题描述

Mooing Duck 发表了评论这里一个函数不能返回多个类型。但是,你可以专门化或委托重载,罚款。

Mooing Duck makes a comment here that "One function can't return multiple types. However, you can specialize or delegate to overloads, which works fine."

我开始思考这个问题,我想知道这个法律代码是什么:

I started thinking about that, and I'm trying to figure out, how is this legal code:

template <typename T>
T initialize(){ return T(13); }

当调用时:

auto foo = initialize<int>();
auto bar = initialize<float>();

不是那个翻译成同名的两个函数只被返回类型重载? p>

Doesn't that translate to 2 functions of the same name overloaded by return-type only?

推荐答案

这不是一个重载,它是一个专业化。它们是不同的机制(事实上混合两者可能导致混乱,因为超载在专业化之前被解决 - 参见Sutter's Mill文章例如: http://www.gotw.ca/publications/mill17.htm )。

It's not an overload, it's a specialization. They are different mechanisms (in fact mixing the two can lead to confusion, because overloads are resolved before specializations are considered -- see this Sutter's Mill article for example: http://www.gotw.ca/publications/mill17.htm).

这篇关于按返回类型重载模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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