简体   繁体   English

数字类型的C ++非零默认值-重新发明吗?

[英]C++ non-zero default value for numeric types - reinvention?

I have in mind a construct like this: 我想到了这样的构造:

template <typename T, T defaultValue>
struct Numeric
{
    Numeric(T t=defaultValue) : value(t) { }
    T value;
    T operator=()(T t);
    operator T();
};

I might use it like this: 我可能会这样使用:

std::vector<Numeric<bool, true> > nothingButTheTruth;

My question is simple: Is this a good approach and if so, does something like this exist in a standard library or Boost? 我的问题很简单:这是一种好方法吗?如果是,那么在标准库或Boost中是否存在类似的东西?

The pattern I see more commonly is to parameterize the container, not the type. 我通常看到的模式是参数化容器,而不是类型。

There are a lot of downsides to doing it your way: 按照自己的方式进行操作有很多弊端:

  • While you provide assignment and conversion, you can't actually bind a bool& to a Numeric<bool, true> . 提供分配和转换时,实际上不能将bool&绑定到Numeric<bool, true>
  • A vector<bool> and a vector<Numeric<bool, true> > are unrelated types. vector<bool>vector<Numeric<bool, true> >是不相关的类型。

This gets pretty painful pretty quickly. 这很快变得非常痛苦。 I wouldn't do it, but perhaps you have a strong use case. 我不会这样做,但是也许您有一个强大的用例。

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

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