【发布时间】:2014-12-12 02:06:44
【问题描述】:
我在cppreference.com 找到了这个示例,它似乎是整个 StackOverflow 中使用的实际示例:
template<int N>
struct S {
int a[N];
};
当然,非类型模板化比这个例子更有价值。此语法还支持哪些其他优化?为什么要创建它?
我很好奇,因为我的代码依赖于已安装的单独库的版本。我在嵌入式环境中工作,所以优化很重要,但我也希望有可读的代码。话虽如此,我想使用这种模板风格来处理版本差异(下面的示例)。首先,我是否正确地考虑了这一点,最重要的是与使用 #ifdef 语句相比,它提供了好处还是缺点?
尝试 1:
template<int VERSION = 500>
void print (char *s);
template<int VERSION>
void print (char *s) {
std::cout << "ERROR! Unsupported version: " << VERSION << "!" << std::endl;
}
template<>
void print<500> (char *s) {
// print using 500 syntax
}
template<>
void print<600> (char *s) {
// print using 600 syntax
}
OR - 由于模板在编译时是常量,编译器是否可以使用类似于以下语法的 if 语句的其他分支来考虑死代码:
尝试 2:
template<int VERSION = 500>
void print (char *s) {
if (VERSION == 500) {
// print using 500 syntax
} else if (VERSION == 600) {
// print using 600 syntax
} else {
std::cout << "ERROR! Unsupported version: " << VERSION << "!" << std::endl;
}
}
是否会尝试产生与此大小相当的输出?
void print (char *s) {
#if defined(500)
// print using 500 syntax
#elif defined(600)
// print using 600 syntax
#else
std::cout << "ERROR! Unsupported version: " << VERSION << "!" << std::endl;
#endif
}
如果你看不出我对这一切有些迷惑,那么就我而言,解释越深入越好。
【问题讨论】:
标签: c++ templates compiler-optimization non-type