Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;数字类型的非零默认值-重新创建?_C++_Templates_Boost_Types_Default Value - Fatal编程技术网

C++ C++;数字类型的非零默认值-重新创建?

C++ C++;数字类型的非零默认值-重新创建?,c++,templates,boost,types,default-value,C++,Templates,Boost,Types,Default Value,我有这样一个想法: 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; 模板 结构数值

我有这样一个想法:

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;
模板
结构数值
{
数值(T=defaultValue):值(T){}
T值;
T算子=()(T);
算子T();
};
我可以这样使用它:

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;
std::向量虚无但真实;

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

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

按你的方式做有很多缺点:

  • 虽然提供赋值和转换,但实际上不能绑定 a
    bool&
    到a
    Numeric
  • 向量
    向量
    是不相关的 类型

这会很快变得很痛苦。我不会这么做,但也许您有一个强大的用例。

是的,没错。但是我的类型不会总是这样包含,所以我可能是一个坏例子。有趣的是,你用
vector
作为例子,就像
vector
那样臭名昭著。@Spire我只使用
bool
,因为OP做了。但我承认我从来都不知道
vector
是如此专业化(但我也从来没有使用过
vector
)。另一个相信新语言可以很快学会的原因是,它们的标准库完全是另一回事。很难想象在不直接指定初始值设定项的情况下,会出现什么样的结果。例如,在向量中,您会说
v.resize(10,true)