#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;
}
如图程序,为什么会有编译时错误呢?明明走了另一个分支啊!
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.