【发布时间】:2020-04-15 15:43:26
【问题描述】:
我知道这个问题有两个答案——一个很长很复杂,一个很短很简单。目前,我对后者感兴趣。
我来自 C#/.NET 背景,如果您使用它一段时间(或 Java),您可能会同意我的观点,即每当您使用某些 BCL 类或方法时,相对容易推断出为什么选择某些重载编译器。
C#的简单例子
// lets imagine we have this somewhere in our code
Contract.Requires(e != null);
// we check who implements this method ...
public static void Requires(bool condition); // <-- observing the call its pretty obvious that this method will be chosen instead of the others
public static void Requires<TException>(bool condition, string userMessage) where TException : Exception;
public static void Requires<TException>(bool condition) where TException : Exception;
public static void Requires(bool condition, string userMessage);
如果您还没有弄清楚我仍在尝试学习 C++,那么我将举一个简单的例子,希望在回答完这个问题后我会开始对阅读 std 代码感到更自在。
// we have this call
int ints[5];
std::is_heap(std::begin(ints), std::end(ints));
// first method I tried to unwind was std::begin and std::end
// and this is what I got from Visual Studio as suggestion (and later confirmed by runtime)
template <class _Ty, size_t _Size>
_NODISCARD constexpr _Ty* begin(_Ty (&_Array)[_Size]) noexcept {
return _Array;
}
template <class _Ty, size_t _Size>
_NODISCARD constexpr _Ty* end(_Ty (&_Array)[_Size]) noexcept {
return _Array + _Size;
}
// then I checked std::is_heap and I got
template <class _RanIt>
_NODISCARD bool is_heap(_RanIt _First, _RanIt _Last) { // test if range is a heap ordered by operator<
return _STD is_heap(_First, _Last, less<>());
}
在我做出一些假设之前,我想我会提醒你我是 C++ 新手的免责声明。
-
(&_Array)[_Size]是否以某种方式帮助编译器理解传递给某个函数(或函数模板)的参数将是数组(类似于type_traits)? - 在第二个静态绑定 (std::is_heap) 中,是不是因为模板是编译时的,因此建议的函数看起来不像您期望的那样,例如,
is_heap(int*, int*),因为这些是调用它的参数类型?
【问题讨论】:
标签: c++ stl std static-linking