我有以下代码片段试图理解 std::enable_if。
使用 godbolt,我注意到我几乎可以在每个编译器上工作(gcc 6.3.0 及更高版本),但它不能在任何版本的 MSVC 上编译(在 msvc 2015、2017、2019 上测试)。
#include <cstdint>
#include <iostream>
template <typename T, typename std::enable_if<(std::is_arithmetic<T>::value), bool>::type = true>
constexpr std::size_t bitSize()
{
return sizeof(T) * 8;
}
template <typename T, typename std::enable_if <(bitSize<T>() == 8), bool>::type = true>
void f(T val) {
std::cout << "f val = " << val << std::endl;
}
int main()
{
uint8_t u8 = 1;
f<uint8_t>(u8);
return 1;
}
Run Code Online (Sandbox Code Playgroud)
MSVC 编译器返回:
main.cpp(10,49): error C2672: 'bitSize': no matching overloaded function found …Run Code Online (Sandbox Code Playgroud)