按返回类型重载模板 [英] Overloading template by Return Type
问题描述
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屋!