MSVC 无法编译 SFINAE 检查

MSVC fails to compile SFINAE checks

本文关键字:SFINAE 检查 编译 MSVC      更新时间:2023-10-16

我应该注意一些编译器标志吗?以下代码工作正常,并且符合GCC和Clang的预期,但不是MSVC。是什么让std::allocator的分配在这里如此不同?

#include <type_traits>
#include <memory>
template <typename T, typename = std::void_t<>>
constexpr bool declares_allocate = false;
template <typename T>
constexpr bool declares_allocate<T, std::void_t<decltype(&T::allocate)>> = true;
struct normal_struct {
auto allocate() -> void {}
};
template <typename T>
struct struct_template {
auto allocate() -> void {}
};
template <typename T>
class class_template_public {
public:
auto allocate() -> void {}
};
template <typename T>
class class_template_private {
private:
auto allocate() -> void {}
};

auto main() -> int {
auto allocator = std::allocator<float>();
auto memory = allocator.allocate(1024);
static_assert(declares_allocate<normal_struct>);                    // pass
static_assert(declares_allocate<struct_template<float>>);           // pass
static_assert(declares_allocate<class_template_public<float>>);     // pass
//  static_assert(declares_allocate<class_template_private<float>>);    // fails
static_assert(declares_allocate<std::allocator<float>>);            // fails when compiled by MSVC but not Clang or GCC
allocator.deallocate(memory, 1024);
return 0;
}

https://godbolt.org/z/GVyNQZ

根据C++标准实现,std::allocator<T>::allocate可以定义为:


T* allocate(size_t n, const void* hint = 0);

T* allocate(size_t n);
T* allocate(size_t n, const void* hint); // deprecating usage of hint

T* allocate(size_t n);

也就是说,第二个实现将allocate转换为重载成员函数。这个目前在MSVC的标准库中使用:

_NODISCARD __declspec(allocator) _Ty* allocate(_CRT_GUARDOVERFLOW const size_t _Count) {
return static_cast<_Ty*>(_Allocate<_New_alignof<_Ty>>(_Get_size_of_n<sizeof(_Ty)>(_Count)));
}
_CXX17_DEPRECATE_OLD_ALLOCATOR_MEMBERS _NODISCARD __declspec(allocator) _Ty* allocate(
_CRT_GUARDOVERFLOW const size_t _Count, const void*) {
return allocate(_Count);
}

这种实现使&T::allocate模棱两可,因此在替换过程中被拒绝。