如果我定义一个接受模板参数的 struct
模板 Bar
:
template <template <int,bool,char> class>
struct Bar {};
我可以使用 struct
模板来实例化它,例如 Zod
:
template <int,bool,char> struct Zod {};
Bar<Zod> a;
我也可以使用嵌套的 struct
模板来实例化它,例如 JKL
:
struct GHI {
template <int,bool,char>
struct JKL {};
};
Bar <GHI::JKL> b;
为什么我不能使用嵌套的可变参数 struct
模板(例如 DEF
)来实例化 Bar
?:
template <typename ...Ts>
struct ABC {
template <Ts ...>
struct DEF {};
};
Bar<ABC<int,bool,char>::DEF> c;
G++ 4.9.2 提示类型/值不匹配;而 Clang 3.4.2 的错误报告模板模板参数的模板参数与其对应的模板模板参数不同。
最佳答案
让我们给 DEF 的参数包起一个名字以便于引用:
template <typename ...Ts>
struct ABC {
template <Ts ... Values>
struct DEF {};
};
这里的重点是通过[temp.param]/p15,Ts...Values
是bothTs
的pack扩展> 和参数包 Values
的声明。
If a template-parameter is [...] a parameter-declaration that declares a parameter pack (8.3.5), then the template-parameter is a template parameter pack (14.5.3). A template parameter pack that is a parameter-declaration whose type contains one or more unexpanded parameter packs is a pack expansion.
由于DEF
采用非类型参数包,它不匹配不带包的模板模板参数([temp.arg.template]/p3):
A template-argument matches a template template-parameter P when each of the template parameters in the template-parameter-list of the template-argument’s corresponding class template or alias template A matches the corresponding template parameter in the template-parameter-list of P. Two template parameters match if they are of the same kind (type, non-type, template), for non-type template-parameters, their types are equivalent (14.5.6.1), and for template template-parameters, each of their corresponding template-parameters matches, recursively. When P’s template-parameter-list contains a template parameter pack (14.5.3), the template parameter pack will match zero or more template parameters or template parameter packs in the template-parameter-list of A with the same type and form as the template parameter pack in P (ignoring whether those template parameters are template parameter packs).
可以肯定的是,Values
对于包来说是相当奇怪的 - 对于 ABC
的每个特化,Values
必须包含固定数量的参数 -但根据目前的规则,它仍然是一个包,所以适用于包的规则。
关于c++ - 为什么这个嵌套的可变参数模板是无效参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30292955/