特定值的C++模板特化

tak*_*kka 6 c++ templates partial-specialization template-specialization c++11

我已经结构Opers与算术操作:mult(),div(),mod().

我需要专门为某些值的模板n.这是一个例子Opers<1>.

但是,我也想做专门化,n因为2的幂(n = 2,4,8,16,...) - 在这种情况下,我可以优化操作mult()div()(使用左或右按位移位).

#include <iostream>
using namespace std;
template<int n> struct Opers {
    int mult(int x){
        return n*x;
    }
    int div(int x){
        return x / n;
    }   
    int mod(int x){
        return x % n;
    }   
};
template<> struct Opers<1> {
    int mult(int x){
        return 1;
    }
    int div(int x){
        return x;
    }   
    int mod(int x){
        return 0;
    }           
};
int main() {
    Opers<1> el2;
    cout << el2.mult(3) <<endl;
} 
Run Code Online (Sandbox Code Playgroud)

我正在寻找像这样的建筑

template<> struct Opers<isPowerOfTwo()>
    int mult(int x){
        // do smth
     }
Run Code Online (Sandbox Code Playgroud)

是否有可能或我应该阅读哪些手册?

UPD.允许使用C++ 11,甚至会更好.

And*_*owl 6

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

template<int n, typename = void>
struct Opers 
{
    // ...
};
Run Code Online (Sandbox Code Playgroud)

然后,编写一个constexpr函数来确定整数是否为2的幂:

constexpr bool is_power_of_two(int x)
{
    return (x == 1) || ((x % 2 == 0) && is_power_of_two(x / 2));
}
Run Code Online (Sandbox Code Playgroud)

最后,使用SFINAE根据您的constexpr函数结果启用或禁用特化:

#include <type_traits>

template<int n>
struct Opers<n, typename std::enable_if<is_power_of_two(n)>::type>
{
    // ...
};
Run Code Online (Sandbox Code Playgroud)

  • 不会`x&(x - 1)== 0`检查同样的事情? (2认同)
  • @soon:也许,是的,但我发现我的版本更容易理解.而且,这是在编译时完成的,因此性能不太可能成为问题 (2认同)