C++ 我们可以使用比模板中更少的参数来声明类模板吗?
map的类模板如下所示C++ 我们可以使用比模板中更少的参数来声明类模板吗?,c++,templates,C++,Templates,map的类模板如下所示 template < class Key, // map::key_type class T, // map::mapped_type class Compare = less<Key>, // map::key_compare
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;
template类图;
从模板上看,它似乎有4个模板参数,但在声明映射时,我只看到两个模板参数
map <int, int> table;
map表;
这不是问题吗?如果不是,那么只定义最后两个(四个)的类型是否正确
map
这不是问题吗
不,这就是默认类型定义的用途:=less
和=allocator
如您所见,这些类型可以从Key
和T
中推断出来
如果不是,那么只定义最后两个(四个)的类型是否正确<代码>地图
不,那不行
map
,将使用默认参数。i、 e.Compare
将less
,而Alloc
将alloctor
这是模板的默认参数 但最后只能有一个或多个参数是默认参数(即,一旦存在默认参数,该参数之后的所有参数都必须是默认参数。) 因此,您的代码如下所示:
map
这将是错误的
正确的代码如下所示:
map代码>
注:你可以参考思维。in .C++,第二版。卷2。
map<,,int,int>