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;
}

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

阅读 3.7k
1 个回答

这种情况下不是用if的,要用specialization。与你的代码的逻辑等价的语法是:

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;
}

这样才会避免编译器在重载决议的时候把含有语法错误的代码加入编译。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题