模板预编译 - C++模板按unsigned值编译
本文介绍了模板预编译 - 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;
}
如图程序,为什么会有编译时错误呢?明明走了另一个分支啊!
解决方案
这种情况下不是用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;
}
这样才会避免编译器在重载决议的时候把含有语法错误的代码加入编译。
这篇关于模板预编译 - C++模板按unsigned值编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文