C++数字类型的非零默认值 - 重新发明?
我想到了这样的构造:
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中是否存在这样的东西?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我更常见的模式是参数化容器,而不是类型。
按照您的方式进行操作有很多缺点:
从
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:
a
bool&
to aNumeric<bool, true>
.vector<bool>
and avector<Numeric<bool, true> >
are unrelatedtypes.
This gets pretty painful pretty quickly. I wouldn't do it, but perhaps you have a strong use case.