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

浏览:34日期:2023-05-05

问题描述

#include <cstdio>template<unsigned N>int func() { if(N>100) {return 1; } else {static const char c = N; // g++: error, clang++: passstatic const char s[1] = {N}; // both errorprintf('%cn',c);return 0; }}int main() { func<1000>(); return 0;}

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

问题解答

回答1:

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

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

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

相关文章: