问题描述
/** * Return the Kth digit of N with base M * e.g. digit<1024,3,10>() = 0 * digit<54321,2,10>() = 2 */template<unsigned N, unsigned K, unsigned M>constexpr unsigned digit() { return (K==1) ? (N%M) : (digit<N/M,K-1,M>());}int main() { printf('%un', digit<1024,3,10>()); return 0;}
想写一个编译时算某个数N第K位上的数是几的程序,模板应该在K=1时停下来,但是编译器报错了,请教应该如何改正?
clang++ -std=c++11 -Wall -o recursive_template recursive_template.cpprecursive_template.cpp:10:27: fatal error: recursive template instantiation exceeded maximum depth of 256return (K==1) ? (N%M) : (digit<N/M,K-1,M>()); ^
[2016-05-21]感谢几位的回答!与这个写法类似的算一个数字有多少位的程序可以编译运行无误,我并不明白为何一个能编译过,一个不行,因为感觉上差不多。写在这里供大家参考~
/** * Return the number of digits when N is expressed in base M. * e.g. base_digits<0,10> == 1 * base_digits<8,2> == 4 */template<unsigned N, unsigned M>constexpr unsigned base_digits() { return (N<M)?1:(1+base_digits<N/M,M>());}int main() { printf('%un', base_digits<1024,2>()); return 0;}
问题解答
回答1:印象中应该不是这样用的
中止条件好像应该要用特例
你搜搜 模版特例化 看看
回答2:同意楼上。要分清编译时和运行时的区别。你这么写在N为1时仍然会接着往下实例化模板