c++ - 为什么带有默认模板参数的模板不能用作模板模板参数中模板参数较少的模板

标签 c++ templates stl

myTemplateTemplate 期望第二个模板参数是一个带有一个参数的模板。 myDefaultTemplate 是一个有两个参数的模板,第二个参数的默认类型为 int。

在 VS2008 中,我得到编译错误:类模板“myDefaultTemplate”的模板参数列表与模板参数“TT”的模板参数列表不匹配

那么,为什么 myDefaultTemplate 不能用作只有一个参数的模板呢? 如果C++编译器支持,会有什么负面影响吗?

template
<typename T1, typename T2 = int>
class
myDefaultTemplate{
      T1 a;
      T2 b;
};

template
<typename T1, template<typename T2> class TT>
class
myTemplateTemplate{
      T1 a;
      TT<T1> b;
};

int main(int argc, char* argv[]){
      myTemplateTemplate<int, myDefaultTemplate> bar; //error here:      
      return 0;
}

最佳答案

来自标准(见 14.3.3 第 1 段 - [temp.arg.template):

A template-argument for a template template-parameter shall be the name of a class template, expressed as id-expression. Only primary class templates are considered when matching the template template argument with the corresponding parameter; partial specializations are not considered even if their parameter lists match that of the template template parameter.

这意味着模板 myDefaultTemplate 将仅被视为 2 个参数模板。默认参数将不被考虑。

关于c++ - 为什么带有默认模板参数的模板不能用作模板模板参数中模板参数较少的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6626759/

相关文章:

c++ - 空 map 的 map::begin() 的返回值是多少?

c++ - 将值传递给函数时调用什么函数

c++ - 用模板实现虚函数的覆盖机制

c++ - 使用 boost.python 导出 C++ 多态函数的聪明方法

c++ - 将 STL 容器传递给 C 函数的指南

c++ - 为了使函数返回编译时常量值,模板中是否需要 constexpr const Type?

c++ - 使用 Dev C++ 将邮件发送到需要身份验证的 smtp 服务器

c++ - C++模板和参数化的Google测试

c++ - 你能从 volatile 函数中去掉成员的 volatile 吗?

c++ - 如何将三角函数用于模板函数/类?