按 Return 类型重载模板

Overloading template by Return Type

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

我开始思考这个问题,我想弄明白,这个法律法规是怎样的:

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

调用时:

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

这不会转化为仅由 return 类型重载的 2 个同名函数吗?

这不是超载,而是专业化。它们是不同的机制(事实上,将两者混合会导致混淆,因为在考虑专业化之前解决了重载问题——例如,请参阅这篇 Sutter's Mill 文章:http://www.gotw.ca/publications/mill17.htm)。

这是不允许的 return 仅值重载的示例:

int initialize();
float initialize();

OTOH,给定主要模板定义

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

引用自here

In order to compile a function call, the compiler must first perform name lookup, which, for functions, may involve argument-dependent lookup, and for function templates may be followed by template argument deduction. If these steps produce more than one candidate function, then overload resolution is performed to select the function that will actually be called.

initialize<int>initialize<float> 只是上述模板的两个不同实例。它们是两个不同的函数,不会属于同一个潜在重载解析候选列表的一部分。