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,甚至会更好.
在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)
| 归档时间: |
|
| 查看次数: |
1187 次 |
| 最近记录: |