定义方法时,为什么模板排序很重要?
我有以下代码:
template<int n>
struct array_container{double arr[n];};
template<int n>
struct avg{
double first[n], second[n];
template <int q>
array_container<q> get_avg(double p) const;
};
我可以为get_avg
添加一个定义:
template<int n>
template<int q>
array_container<q> avg<n>::get_avg(double p) const{
array_container<q> result;
const int m = min(n,q);
for(int k=0;k<m;k++){result.arr[k] = p*first[k] + (1-p) * second[k];}
return result;
}
如果我要替换定义的前两行,即:
template<int n>
template<int q>
使用其中任何一个:
template<int q>
template<int n>
template<int n, int q>
template<int q, int n>
编译将失败。为什么这样?在定义array_container&lt; q&gt;时,我认为模板的顺序没有意义。 avg&lt; n&gt; :: get_avg(double p)const
。
编辑: 我了解到,在当前标准中,定义中模板参数子句的排序必须与声明的排序完全相对应。我的问题与该语言的设计有关。
与逻辑或一致性有关,有什么原因,为什么我的替代示例不能同样有效?特别是因为如果我向候选人提供“不正确”的订单,则可以推论正确的候选人。
I have the following code:
template<int n>
struct array_container{double arr[n];};
template<int n>
struct avg{
double first[n], second[n];
template <int q>
array_container<q> get_avg(double p) const;
};
I can add a definition for get_avg
like this:
template<int n>
template<int q>
array_container<q> avg<n>::get_avg(double p) const{
array_container<q> result;
const int m = min(n,q);
for(int k=0;k<m;k++){result.arr[k] = p*first[k] + (1-p) * second[k];}
return result;
}
If I were to replace the first two lines of the definition, namely:
template<int n>
template<int q>
with any one of these:
template<int q>
template<int n>
template<int n, int q>
template<int q, int n>
compilation would fail . Why is this so? I see no significance in the order of the templates when defining for array_container<q> avg<n>::get_avg(double p) const
.
Edit:
I understand that in the current standard the ordering of the template parameter clauses in the definition must correspond exactly to that of the declaration. My question is relating to the design of the language.
Is there any reason, relating to logic or consistency, why my alternative examples could not be considered equally as valid? Especially since the compiler can already deduce the correct candidate if I provide it with an "incorrect" ordering.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为当提供 类别定义第一个参数子句
template&lt; int n&gt;
对应于第二个参数strapertemplate&lt; lt; int q&gt;
对应于成员模板get_avg
本身。更重要的是,在为成员模板提供课外定义时,最外面的参数子句(对于类模板(如果有))必须先出现,则为成员模板的子句(如果有)。Because when providing an out-of-class definition the first parameter clause
template<int n>
corresponds to the outermost enclosing class template while the second parameter clausetemplate<int q>
corresponds to the member templateget_avg
itself. More importanty when providing an out-of-class definition for the member template, the outermost parameter clause(for the class template(if any)) must come first, then the clause for the member templates(if any) .