我正在使用类模板扣除指南并尝试递归使用它。但我无法获得以下代码进行编译
#include <type_traits>
template<int N>
using int_const = std::integral_constant<int,N>;
template<int N>
struct Foo{
constexpr static int value = N;
template<int C>
constexpr Foo(int_const<C>){};
};
Foo(int_const<0>) -> Foo<1>;
template<int N>
Foo(int_const<N>) -> Foo<N*(Foo{int_const<N-1>{}}.value)>;
int main(){
return Foo{int_const<5>{}}.value;
}
这是错误:
<source>: In substitution of 'template<int N> Foo(int_const<N>)-> Foo<(N * > Foo{std::integral_constant<int, (N - 1)>{}}.value)> [with int N = -894]': <source>:17:51: recursively required by substitution of 'template<int N> Foo(int_const<N>)-> Foo<(N * Foo{std::integral_constant<int, (N - 1)>{}}.value)> [with int N = 4]' <source>:17:51: required by substitution of 'template<int N> Foo(int_const<N>)-> Foo<(N * Foo{std::integral_constant<int, (N - 1)>{}}.value)> [with int N = 5]' <source>:20:30: required from here <source>:17:1: fatal error: template instantiation depth exceeds maximum of 900 (use -ftemplate-depth= to increase the maximum) Foo(int_const<N>) -> Foo<N*(Foo{int_const<N-1>{}}.value)>; ^~~
编译终止。
你需要一个帮助模板:
template<int N>
struct foo_helper
{ static constexpr int value = N * Foo{int_const<N-1>{}}.value; };
template<>
struct foo_helper<0>
{ static constexpr int value = 1; };
有了这个(也是唯一的)演绎指南:
template<int C>
Foo(int_const<C>)
-> Foo<foo_helper<C>::value>
;
Live demo与Foo{int_const<5>{}}.value
正确评估为120。
为什么会这样?
因为有以下演绎指南
template<int N>
Foo(int_const<N>) -> Foo<N*(Foo{int_const<N-1>{}}.value)>;
当CTAD开始时,所有指南都会被考虑;即使你提供了一个更专业的指南(Foo<0>
),这个递归指南明确专业化,Foo{int_const<N-1>{}}
最终专门针对N=0
,因此无限递归。
引入一个间接层,foo_helper
打破了这种无限递归:你可以专门化一个类,而不是演绎指南。
以下代码有效:
#include <type_traits>
template<int N>
using int_const = std::integral_constant<int,N>;
template<int N>
struct Foo{
constexpr static int value = N;
template<int C>
constexpr Foo(int_const<C>){};
};
template<int N>
constexpr auto previous_foo(){
if constexpr (N<=0){
return 1;
}
else {
return decltype(Foo{int_const<N-1>{}})::value;
}
}
template<int N>
Foo(int_const<N>) -> Foo<(N>0)?N*previous_foo<N>():1>;
int main(){
return Foo{int_const<5>{}}.value;
}