简体   繁体   English

特定值的C ++模板特化

[英]C++ template specialization for specific values

I have struct Opers with some arithmetic operations: mult() , div() , mod() . 我有一些带有算术运算的struct Opersmult()div()mod()

And I need to specialize template for certain values of n . 我需要为n某些值专门化模板。 Here is example for Opers<1> . 以下是Opers<1>示例。

But, also I want to do specialization for n that are powers of 2 ( n = 2,4,8,16, ...) – in this case I can optimize operations mult() and div() (using bitwise shift left or right). 但是,我也想为做到专业化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;
} 

I'm looking for construction like 我正在寻找像这样的建筑

template<> struct Opers<isPowerOfTwo()>
    int mult(int x){
        // do smth
     }

Is it possible or what manual should I read? 是否有可能或我应该阅读哪些手册?

UPD. UPD。 Using C++11 is allowed, and even would be better. 允许使用C ++ 11,甚至会更好。

In C++11, you could do it this way. 在C ++ 11中,你可以这样做。 First of all, change your primary template so that it accepts a second, dummy parameter: 首先,更改主模板,使其接受第二个虚拟参数:

template<int n, typename = void>
struct Opers 
{
    // ...
};

Then, write a constexpr function that determines whether an integer is a power of 2: 然后,编写一个constexpr函数,用于确定整数是否为2的幂:

constexpr bool is_power_of_two(int x)
{
    return (x == 1) || ((x % 2 == 0) && is_power_of_two(x / 2));
}

Finally, use SFINAE to enable or disable the specialization based on the result of your constexpr function: 最后,使用SFINAE根据constexpr函数的结果启用或禁用特化:

#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
{
    // ....
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM