[英]Nested template parameters for functions
template <typename T> class foo2 {
};
Sample 1 样品1
template <typename T, template <typename> class foo2>
foo2<T> func2(){
}
Sample 2 样品2
template <template <typename T> class foo2>
foo2<T> func2(){
}
I have a template class and I would like to write a function that accepts only that class (with any of it's templates of course) why does sample 1 works and 2 does not? 我有一个模板类,我想编写一个仅接受该类的函数(当然也可以使用任何一个模板),为什么样本1有效而样本2不起作用?
Edit: 编辑:
Please provide an explanation of how the matching happens? 请说明匹配如何发生? Clearly the function in sample 1 takes two template parameters without any default values, however in the call in the main only one parameter is provided.
显然,示例1中的函数采用两个模板参数,而没有任何默认值,但是在主调用中,仅提供了一个参数。
Edit2: I want another func2 overload for the templated foo2 class, I already have defined in my code. Edit2:我想为模板化的foo2类提供另一个func2重载,我已经在代码中定义了。
template <typename T>
T func2(){
}
Template template parameters define a template name in the body of the function. 模板模板参数在函数主体中定义模板名称。 You have to provide the parameter to instantiate them.
您必须提供参数以实例化它们。 This means that the
T
in 这意味着
T
in
template <template <typename T> class foo2> void func2(foo2<T>);
is not visible elsewhere; 在其他地方不可见; only the template name
foo2
is. 只有模板名称
foo2
是。
Your first sample, 您的第一个样本
template <typename T, template <typename> class foo2> void func2(foo2<T>);
works because the T is a top-level template type parameter, which is 因为T是顶级模板类型参数,所以它起作用
However, this use case is more easily written with a simple template type parameter and direct use of the class foo2
: 但是,使用简单的模板类型参数并直接使用类
foo2
可以更轻松地编写此用例:
template <typename T> void func2(foo2<T>);
See, for example, template parameters and template arguments on cppreference for details 有关详细信息,请参见例如cppreference上的模板参数和模板参数
Note, the question was edited after I wrote the above, and the type is no longer used as a function argument. 请注意,在我写完上面的内容后,问题已被编辑,类型不再用作函数参数。 The point about type deduction no longer applies, but the rest of the answer stands.
关于类型推导的观点不再适用,但是其余的答案仍然成立。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.