map 的类模板是这样的
template < class Key, // map::key_type
class T, // map::mapped_type
class Compare = less<Key>, // map::key_compare
class Alloc = allocator<pair<const Key,T> > // map::allocator_type
> class map;
从模板来看,它似乎采用 4 个模板参数,但在声明 map 时,我只看到两个模板参数。
map <int, int> table;
这不是问题吗?如果仅定义(四个中的)最后两个的类型不是正确的吗?
map<,,int,int>
最佳答案
- Is this not a problem?
这不是问题,是default template arguments .
Default template arguments are specified in the parameter lists after the = sign.
这意味着当你没有指定它们时,比如map<key_type, value_type>
,将使用默认参数。即 Compare
将是 less<key_type>
, 和 Alloc
将是 allocator<pair<const key_type, value_type>>
.
- is this correct to just define the type of last two(of the four)? map<,,int,int>
没有。默认参数用于代替缺少的尾随 参数。您不能只指定最后两个参数而不指定前两个参数并希望应用默认参数。在这种情况下,前两个参数根本没有默认参数。
顺便说一句
If the default is specified for a template parameter of a primary class template, each subsequent template parameter must have a default argument, except the very last one may be a template parameter pack.
关于c++ - 我们可以使用比模板中更少的参数来声明类模板吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36245644/