c++ - 我们可以使用比模板中更少的参数来声明类模板吗?

标签 c++ templates

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>

最佳答案

  1. 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>> .

  1. 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/

相关文章:

c++ - 为什么不能推导嵌套在模板类中的枚举的模板参数?

c++ - Qt c++ 聚合 'std::stringstream ss' 类型不完整,无法定义

c++ - 同名友元函数和方法

C++ Windows 系统 ("path") 如果某处有空间则不工作

c++ - 使用 Stack 时的段错误到底是什么以及如何修复它?

c++ - 可以对内置类型使用 C 样式转换吗?

c++ - 通用成员函数定义

php - 尝试打印多维数组中的值以形成预设值

c++ - 调试函数包装器

c++ - VS2013 RC中函数模板的过载解决