首页 > C++模板递归超出深度

C++模板递归超出深度

/**
 * 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("%u\n", digit<1024,3,10>());
    return 0;
}

想写一个编译时算某个数N第K位上的数是几的程序,模板应该在K=1时停下来,但是编译器报错了,请教应该如何改正?

clang++ -std=c++11 -Wall -o recursive_template recursive_template.cpp
recursive_template.cpp:10:27: fatal error: recursive template instantiation exceeded
      maximum depth of 256
        return (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("%u\n", base_digits<1024,2>());
    return 0;
}

同意楼上。要分清编译时和运行时的区别。你这么写在N为1时仍然会接着往下实例化模板


印象中应该不是这样用的

中止条件好像应该要用特例

你搜搜 模版特例化 看看

【热门文章】
【热门文章】