由于范围有限,使用模板进行比较总是错误的. [英] Comparison is always false due to limited range ... with templates

查看:53
本文介绍了由于范围有限,使用模板进行比较总是错误的.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对模板类型变量进行操作的模板化函数,如果该值小于0,则将其设置为0.这可以正常工作,但是当我的模板化类型为无符号时,我会收到有关比较总是错误的.这显然是有道理的,但是由于它是模板化的,所以我希望它对所有数据类型(有符号和无符号)通用,而不发出警告.

I have a templated function that operates on a template-type variable, and if the value is less than 0, sets it to 0. This works fine, but when my templated type is unsigned, I get a warning about how the comparison is always false. This obviously makes sense, but since its templated, I'd like it to be generic for all data types (signed and unsigned) and not issue the warning.

我在Linux上使用g ++,并且我猜想有一种方法可以通过g ++的命令行选项来抑制该特定警告,但是我仍然希望在其他非模板化的情况下获得该警告.我想知道代码中是否有某种方法可以防止这种情况,而不必编写该函数的多个版本?

I'm using g++ on Linux, and I'm guessing there's a way to suppress that particular warning via command line option to g++, but I'd still like to get the warning in other, non-templated, cases. I'm wondering if there's some way, in the code, to prevent this, without having to write multiple versions of the function?

template < class T >
T trim(T &val)
{
  if (val < 0)
  {
    val = 0;
  }
  return (val);
}
int main()
{
  char cval = 5;
  unsigned char ucval = 5;

  cout << "Untrimmed: " << (int)cval;
  cval = trim(cval);
  cout << " Trimmed: " << (int)cval << endl;

  cout << "Untrimmed: " << (int)ucval;
  cval = trim(ucval);
  cout << " Trimmed: " << (int)ucval << endl;

 return (0);
}

推荐答案

#include <algorithm>

template<class T>
T& trim(T& val) {
  val = std::max(T(0), val);
  return val;
}

从这个问题来看,通过非常量引用传递是否合适并不明显.您可以更改以上任何内容(无效),按值传递和按值返回或按const&并按值返回:

It's not apparent from the question that passing by non-const reference is appropriate. You can change the above return nothing (void), pass by value and return by value, or pass by const& and return by value:

template<class T>
T trim(T const& val);

// example use:
value = trim(value); // likely the most clear solution

一般化一点,即使在您的问题范围:

Generalize a bit more, even though outside the scope of your question:

template<class T>
T constrain(T const& value, T const& lower, T const& upper) {
  // returns value if value within [lower, upper] (inclusive end points)
  // returns lower if value < lower
  // otherwise returns upper
  assert(lower <= upper); // precondition
  return std::min(std::max(value, lower), upper);
}

template<class T>
T constrain_range(T const& value, T const& lower, T const& upper) {
  // returns value if value within [lower, upper) (exclusive upper)
  // returns lower if value < lower
  // otherwise returns upper - 1
  assert(lower < upper); // precondition
  if      (value <  lower) return lower;
  else if (value >= upper) return upper - 1;
  else                     return value;
}

这篇关于由于范围有限,使用模板进行比较总是错误的.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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