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

发布于 2024-12-29 13:41:35 字数 371 浏览 4 评论 0 原文

我想到了这样的构造:

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

我可能会这样使用它:

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

我的问题很简单:这是一个好的方法吗?如果是的话,标准库或Boost中是否存在这样的东西?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初见终念 2025-01-05 13:41:35

我更常见的模式是参数化容器,而不是类型。

按照您的方式进行操作有很多缺点:

  • 当您提供赋值和转换时,您实际上无法绑定
    bool&Numeric
  • 向量向量 > 不相关
    类型。

这很快就会变得非常痛苦。我不会这样做,但也许你有一个强大的用例。

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>.
  • A vector<bool> and a vector<Numeric<bool, true> > are unrelated
    types.

This gets pretty painful pretty quickly. I wouldn't do it, but perhaps you have a strong use case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文