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++;特定值的模板专门化_C++_Templates_C++11_Template Specialization_Partial Specialization - Fatal编程技术网

C++ C++;特定值的模板专门化

C++ C++;特定值的模板专门化,c++,templates,c++11,template-specialization,partial-specialization,C++,Templates,C++11,Template Specialization,Partial Specialization,我有带一些算术运算的struct操作符:mult(),div(),mod() 我需要为n的某些值专门化模板。下面是操作的示例 但是,我还想对n进行专门化,它们是2的幂(n=2,4,8,16,…)——在这种情况下,我可以优化操作mult()和div()(使用按位向左或向右移位) #包括 使用名称空间std; 模板结构操作{ 整数倍(整数倍){ 返回n*x; } 内部分区(内部x){ 返回x/n; } 整数模(整数x){ 返回x%n; } }; 模板结构操作{ 整数倍(整数倍){ 返回1

我有带一些算术运算的struct
操作符:
mult()
div()
mod()

我需要为
n
的某些值专门化模板。下面是
操作的示例

但是,我还想对
n
进行专门化,它们是2的幂(n=2,4,8,16,…)——在这种情况下,我可以优化操作
mult()
div()
(使用按位向左或向右移位)

#包括
使用名称空间std;
模板结构操作{
整数倍(整数倍){
返回n*x;
}
内部分区(内部x){
返回x/n;
}   
整数模(整数x){
返回x%n;
}   
};
模板结构操作{
整数倍(整数倍){
返回1;
}
内部分区(内部x){
返回x;
}   
整数模(整数x){
返回0;
}           
};
int main(){
操作el2;

在C++11中,可以这样做。首先,更改主模板,使其接受第二个伪参数:

template<int n, typename = void>
struct Opers 
{
    // ...
};
最后,使用SFINAE根据
constexpr
函数的结果启用或禁用专门化:

#include <type_traits>

template<int n>
struct Opers<n, typename std::enable_if<is_power_of_two(n)>::type>
{
    // ...
};
#包括
模板
结构操作器
{
// ...
};
模板
结构操作
{
// ....
};
模板
结构操作
{
// ....
};

Ahh…使用移位优化。编译器会像“哇,我从来没有想到过那样”…我知道这对编译器来说并不重要!这只是一个例子(与我的学习任务相关),我找不到正确的结构或方法来编写不会
x&(x-1)的代码==0
检查同样的事情吗?@soon:也许,是的,但我发现我的版本更容易理解。而且,这是在编译时完成的,所以性能不太可能是个问题
模板
呢?@DyP:这也是一种可能性,但我认为我的解决方案更通用,因为它允许添加新的专门化,而无需更改主模板非常感谢!这正是我要找的!
template<int n, typename = void>
struct Opers 
{
    // ...
};
constexpr bool is_power_of_two(int x)
{
    return (x == 1) || ((x % 2 == 0) && is_power_of_two(x / 2));
}
#include <type_traits>

template<int n>
struct Opers<n, typename std::enable_if<is_power_of_two(n)>::type>
{
    // ...
};
template <int N, typename = void>
struct Operations
{
    // ....
};

template <int N, typename = std::enable_if<(N & (N - 1))>::type>
struct Operations
{
    // ....
};