Home  >  Q&A  >  body text

模板预编译 - C++模板按unsigned值编译

#include <cstdio>

template<unsigned N>
int func() {
    if(N>100) {
        return 1;
    } else {
        static const char c = N; // g++: error, clang++: pass
        static const char s[1] = {N}; // both error
        printf("%c\n",c);
        return 0;
    }
}

int main() {
    func<1000>();
    return 0;
}

如图程序,为什么会有编译时错误呢?明明走了另一个分支啊!

天蓬老师天蓬老师2715 days ago618

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 13:46:48

    In this case, if is not used, but specialization is used. The syntax that is logically equivalent to your code is:

    template<unsigned N>
    std::enable_if<(N <= 100), int>::type
    func() {
        static const char c = N; // g++: error, clang++: pass
        static const char s[1] = {N}; // both error
        printf("%c\n",c);
        return 0;
    }
    
    template<unsigned N>
    std::enable_if<(N > 100), int>::type
    func() {
        return 1;
    }

    This will prevent the compiler from adding code containing syntax errors to the compilation during overload resolution.

    reply
    0
  • Cancelreply