考虑范例max模板函数,std::max():
// From the STL
// TEMPLATE FUNCTION _Debug_lt
template<class _Ty1, class _Ty2> inline
bool _Debug_lt(const _Ty1& _Left, const _Ty2& _Right,
_Dbfile_t _File, _Dbline_t _Line)
{ // test if _Left < _Right and operator< is strict weak ordering
if (!(_Left < _Right))
return (false);
else if (_Right < _Left)
_DEBUG_ERROR2("invalid operator<", _File, _Line);
return (true);
}
// intermediate #defines/templates skipped
// TEMPLATE FUNCTION max
template<class _Ty> inline
const _Ty& (max)(const _Ty& _Left, const _Ty& _Right)
{ …Run Code Online (Sandbox Code Playgroud) 为什么以下代码无法编译(gcc-5.4.0)?
volatile int i{100};
int j{200};
std::cout << std::min(i, j);
Run Code Online (Sandbox Code Playgroud)
我的意思是我看到编译器错误:
错误:没有匹配函数来调用'min(volatile int&,int&)'
是不是volatile只是提示编译器,该变量可能会从程序外部改变?
std::min(int(i), j);
Run Code Online (Sandbox Code Playgroud)
当然是有效的.但是不应该原创作品吗?
您可能知道std::max并std::min“受苦”,因为它们有 1 个模板参数,因此即使简单max(container.size(), 47)也行不通,因为 .size() 返回size_t而 47 是int。
我知道历史上曾有人提议向 C++ 添加适当的重载,但被拒绝了。但据我所知,这主要是由于纸张过于复杂而无法获得足够的收益,所以我想知道是否可以将其std::common_range_t用作返回值(发明的类型特征使您的 int/float 足够大以容纳混合参数的最小值/最大值,否则会出现硬错误)那会好吗...
所以最终得到我的问题:如果我们希望 min/max 扩展为采用 2 如上所述的模板参数,是否有任何向后兼容性或任何其他问题阻止了这一点?
笔记: