优雅的方式来表达左移或右在模板 [英] Elegant way to express shift left OR right in template

查看:132
本文介绍了优雅的方式来表达左移或右在模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个模板函数,根据模板参数A和B,可以向左或向右移动一个值:

  template< int A,int B> void f(X){
// ...
if(A> = B)
{
SetValue(X<(A-B));
}
else //(A< B)
{
SetValue(X>>(B-A));
}



当我实例化 A& / code>,我得到一个负移位的警告在(不可达)第一分支,否则我得到一个负移位留在第一分支的警告。我们的代码库是无警告的,所以这是不能接受的。



类似的问题(例如动态左移或右移)没有这个虚假警告,因为移动距离是一个运行时变量。

 模板< int A,int B> 
void f_impl(typename std :: enable_if<(A> = B)> :: type * = 0)
{
//第一种情况
} $ b b
template< int A,int B>
void f_impl(typename std :: enable_if<(A< B)> :: type * = 0)
{
//第二种情况
}

template< int A,int B>
void f()
{
f_impl< A,B>();
}


I currently have a template function which, depending on its template parameters A and B, may shift a value either left or right:

template <int A, int B> void f(X) {
// ...
if (A >= B)
{
  SetValue(X << (A-B));
}
else // (A < B)
{
  SetValue(X >> (B-A));
}

When I instantiate the template for A<B, I get a warning for a negative shift right on the (unreachable) first branch, and else I get a warning for a negative shift left on the first branch. Our codebase is warning-free so this isn't acceptable. Is there a concise, readable alternative to these two shift statements?

Similar questions (e.g. Dynamically shift left OR right) don't have this spurious warning as the shift distance is a runtime variable there.

解决方案

With C++11 or boost.

template<int A, int B>
void f_impl(typename std::enable_if<(A >= B)>::type* = 0)
{
   // first case
}

template<int A, int B>
void f_impl(typename std::enable_if<(A < B)>::type* = 0)
{
   // second case
}

template<int A, int B>
void f()
{
   f_impl<A, B>();
}

这篇关于优雅的方式来表达左移或右在模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆