C++ 基于参数的正性专门化模板
给定一个模板C++ 基于参数的正性专门化模板,c++,templates,math,C++,Templates,Math,给定一个模板 template <int n> void f(){...}; 但是,有没有一种方法可以让我专门针对所有的阳性n 我想做以下几件事 template <int n> void f<n>(){ int dummy[n]; //invalid for n < 0 ... }; 模板 void f(){ int dummy[n];//对于n
template <int n>
void f(){...};
但是,有没有一种方法可以让我专门针对所有的阳性n
我想做以下几件事
template <int n>
void f<n>(){
int dummy[n]; //invalid for n < 0
...
};
模板
void f(){
int dummy[n];//对于n<0无效
...
};
因此,对于
n来说,一个选项是使用另一个间接级别。定义一个包含两个参数的辅助模板-数字n
和表示n
是否为负的bool
,然后在n
为负时专门化该模板。然后,让f
函数用正确的参数实例化模板
例如:
template <int n, bool isNegative> struct fImpl {
static void f() {
/* ... code for when n is positive ... */
}
};
template <int n> struct fImpl<n, true> {
static void f() {
/* ... code for when n is negative ... */
}
};
template <int n> void f() {
fImpl<n, (n < 0)>::f();
}
如果n
具有正确的符号,则这些函数中的每一个都只能用于重载解析,因此将始终调用正确的版本
希望这有帮助 风格方面的问题,但我更喜欢将enable\u if
放在返回类型上,这样就不会有一个神奇的参数让人困惑(用户和函数类型)。
template <int n, bool isNegative> struct fImpl {
static void f() {
/* ... code for when n is positive ... */
}
};
template <int n> struct fImpl<n, true> {
static void f() {
/* ... code for when n is negative ... */
}
};
template <int n> void f() {
fImpl<n, (n < 0)>::f();
}
template <int n> void f(typename std::enable_if<(n < 0)>::type* = 0) {
/* ... n is negative ... */
}
template <int n> void f(typename std::enable_if<(n >= 0)>::type* = 0) {
/* ... n is positive ... */
}