SFINAEついて勉強中にわからないことがありました
詳細は長くなってしまったので、始めに単純化して書きます
主旨としては、どのようにf()
を呼び出せば次のコードがコンパイル可能になるのだろうかということになると思います
#include <type_traits>
#include <iostream>
template <typename T, typename std::enable_if<std::is_integral<T>::value>::type>
void f()
{
std::cout << "ok" << std::endl;
}
int main()
{
f<int>();
}
詳細
変更前
template <class _Tp>
_LIBCPP_INLINE_VISIBILITY
static
typename enable_if
<
(__is_default_allocator<allocator_type>::value
|| !__has_construct<allocator_type, _Tp*, _Tp>::value) &&
is_trivially_move_constructible<_Tp>::value,
void
>::type
__construct_forward_with_exception_guarantees(allocator_type&, _Tp* __begin1, _Tp* __end1,
{
ptrdiff_t _Np = __end1 - __begin1;
if (_Np > 0)
{
_VSTD::memcpy(__begin2, __begin1, _Np * sizeof(_Tp));
__begin2 += _Np;
}
}
変更後
template <class _Alloc, class _Tp, typename enable_if<
(__is_default_allocator<_Alloc>::value || !__has_construct<_Alloc, _Tp*, _Tp>::value) &&
is_trivially_move_constructible<_Tp>::value
>::type>
_LIBCPP_INLINE_VISIBILITY
void __construct_forward_with_exception_guarantees(_Alloc&, _Tp* __begin1, _Tp* __end1, _Tp*& __begin2) {
ptrdiff_t _Np = __end1 - __begin1;
if (_Np > 0) {
_VSTD::memcpy(__begin2, __begin1, _Np * sizeof(_Tp));
__begin2 += _Np;
}
}
変更前は戻り値にenable_ifが使用されていて、trueの場合、
void __construct_forward_with_exception_guarantees(略)
として実体化されるのに対して、
変更後は
template <class _Alloc, class _Tp, void> void __construct_forward_with_exception_guarantees(略)
のようになりそうで、どうすれば実体化できるのか疑問に思っています。
※追記 現在のllvm最新versionでは別の関数に置き換わっていました
https://github.com/llvm/llvm-project/commit/23cf42e706fbc2a939ce1470da16599b42258aea
余談
発端は、次の(未定義な動作をする)コードを異なるmacで実行した場合に一方はsegv, もう一方は正常終了したことです
(llvmの具体的なversionは今手元にないので書けません、すいません)
#include <vector>
int main()
{
std::vector<size_t> v;
size_t a[2] = {0, 1};
v.reserve(1);
v.insert(v.end() + 1, a, a + 2);
}
segvした方のmacでは__construct_forward_with_exception_guarantees
が変更後の実装で、先述のenable_ifの方は選択されず、
https://github.com/llvm/llvm-project/blob/229db3647491ed2b2706a9b9ce13a97e38be6fa0/libcxx/include/memory#L1461
template <class _Ptr>
_LIBCPP_INLINE_VISIBILITY
static
void
__construct_forward_with_exception_guarantees(allocator_type& __a, _Ptr __begin1, _Ptr __end1, _Ptr& __begin2)
{
static_assert(__is_cpp17_move_insertable<allocator_type>::value,
"The specified type does not meet the requirements of Cpp17MoveInsertible");
for (; __begin1 != __end1; ++__begin1, (void) ++__begin2)
construct(__a, _VSTD::__to_address(__begin2),
#ifdef _LIBCPP_NO_EXCEPTIONS
_VSTD::move(*__begin1)
#else
_VSTD::move_if_noexcept(*__begin1)
#endif
);
}
が実体化し、
__begin1 != __end1
の条件が end() + 1 != end();
となって、ループが回り続けることによってsegvしているようでした
一方変更前の実装ではenable_ifの方が実体化し、
ptrdiff_t _Np = __end1 - __begin1;
の結果が負となり、if (_Np > 0)
で弾かれて何もせずに関数を抜けた結果、segvせずに終了しているようでした
オーバーロード解決がなぜこのように振舞うのかわからず、デバッガで追ってみたり、llvmのソースを見てみたりしていましたが、自分ではこれ以上のことはわかりませんでした
よろしくお願いします