search

Home  >  Q&A  >  body text

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;
}
迷茫迷茫2774 days ago378

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:46:44

    I think this is not how it is used

    It seems that a special case should be used for the abort condition

    You search for template specialization and take a look

    reply
    0
  • PHPz

    PHPz2017-04-17 13:46:44

    Agree with the above. It is necessary to distinguish the difference between compile time and run time. If you write this way, when N is 1, the template will still be instantiated

    reply
    0
  • Cancelreply