좋은 하루,무한 재귀 메타의 정수 제곱근
내 친구는 메타 함수에 정수 제곱근 함수를 변환에 대해 요구하고있다. 여기에 원래의 함수입니다 :
unsigned isqrt(unsigned value)
{
unsigned sq = 1, dlt = 3;
while(sq<=value)
{
sq += dlt;
dlt += 2;
}
return (dlt>>1) - 1;
}
내가
constexpr
를 사용하여 메타 버전을 썼다,하지만 그는 어떤 이유로 새로운 기능을 사용할 수 없습니다 말했다
constexpr std::size_t isqrt_impl
(std::size_t sq, std::size_t dlt, std::size_t value){
return sq <= value ?
isqrt_impl(sq+dlt, dlt+2, value) : (dlt >> 1) - 1;
}
constexpr std::size_t isqrt(std::size_t value){
return isqrt_impl(1, 3, value);
}
그래서 나는 그것이 안 생각 하드 재귀 적으로 자기를 호출 템플릿 구조체로 그것을 변환하는 것을 수 :
template <std::size_t value, std::size_t sq, std::size_t dlt>
struct isqrt_impl{
static const std::size_t square_root =
sq <= value ?
isqrt_impl<value, sq+dlt, dlt+2>::square_root :
(dlt >> 1) - 1;
};
template <std::size_t value>
struct isqrt{
static const std::size_t square_root =
isqrt_impl<value, 1, 3>::square_root;
};
불행하게도,이 (GCC 4.6.1)에 무한 재귀를 일으키는 나는 w 무엇이 잘못되었는지 알아낼 수 없습니까 코드 ith. 여기에 오류 :
C:\test>g++ -Wall test.cpp
test.cpp:6:119: error: template instantiation depth exceeds maximum of 1024 (use
-ftemplate-depth= to increase the maximum) instantiating 'struct isqrt_impl<25u
, 1048576u, 2049u>'
test.cpp:6:119: recursively instantiated from 'const size_t isqrt_impl<25u, 4u
, 5u>::square_root'
test.cpp:6:119: instantiated from 'const size_t isqrt_impl<25u, 1u, 3u>::squar
e_root'
test.cpp:11:69: instantiated from 'const size_t isqrt<25u>::square_root'
test.cpp:15:29: instantiated from here
test.cpp:6:119: error: incomplete type 'isqrt_impl<25u, 1048576u, 2049u>' used i
n nested name specifier
모두 감사합니다,
재귀 함수를 사용하여 실제 재귀 깊이를 계산하면 어떻게됩니까? – sharptooth
@sharptooth 모든 값에서 발생합니다. 사용 된 값이 오버플로를 일으키는 것은 아닙니다. – AraK