Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 基于参数的正性专门化模板_C++_Templates_Math - Fatal编程技术网

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 ... */
}