ein*_*ica 5 c++ unique-ptr template-templates c++11 template-argument-deduction
这段代码:
#include <memory>
template <template <typename> class Ptr>
class A { Ptr<int> ints; };
using B = A<std::unique_ptr>;
Run Code Online (Sandbox Code Playgroud)
产生以下错误(使用GCC 6.3):
a.cpp:6:28: error: type/value mismatch at argument 1 in template parameter list for ‘template<template<class> class Ptr> class A’
using B = A<std::unique_ptr>;
^
a.cpp:6:28: note: expected a template of type ‘template<class> class Ptr’, got ‘template<class _Tp, class _Dp> class std::unique_ptr’
Run Code Online (Sandbox Code Playgroud)
现在,我可以解决这个问题,就像这样:
template <typename T>
using plugged_unique_ptr = std::unique_ptr<T>;
using B = A<plugged_unique_ptr>;
Run Code Online (Sandbox Code Playgroud)
但为什么我要这样做?我的意思是,为什么编译器不愿意"插入"第二个模板参数std::unique_ptr及其默认值并允许std::unique_ptr用作模板参数A?
因为模板模板参数需要完全匹配.这意味着默认模板参数在此处不相关.请注意,将模板模板参数扩展为两个模板参数只会偶然发生:允许实现添加比标准定义的模板参数更多的模板参数,有些模板参数通常用于std容器的SFINAE.
这也是我通常建议不要使用任何模板模板参数,而只是使用普通模板类型名称的主要原因.如果您需要访问嵌套模板类型,请提供内部访问器,例如,value_type或者在外部访问器中,tuple_element以便在模板内访问这些访问器.
注意:这显然在C++ 17中发生了变化,其中匹配不再精确,但略微放松但更复杂.不过,我仍然建议不要使用模板模板参数.