英文:
Overloaded template function doesn't select the correct version for a specific type
问题
Situation is: I have a generic function but would like an altered version for a specific type.
I would instinctively write a widget const&
w parameter to be able to accept any widget by reference, but that doesn't compile in that case, because the compiler ignored the specific overload (2) and used generic (1) instead. It does compile if I remove the const in the params of (2), why is that?
struct widget {
int widget_size;
};
// (1)
// compiler uses this instead of (2)
template <typename Arg>
int get_size(Arg && arg) {
return arg.size;
}
// (2)
int get_size(widget const& arg) {
return arg.widget_size;
}
int main() {
widget w;
get_size(w);
}
英文:
Situation is: I have a generic function but would like an altered version for a specific type.
I would instinctively write a widget const& w
parameter to be able to accept any widget by reference, but that doesn't compile in that case, because the compiler ignored the specific overload (2) and used generic (1) instead. It does compile if I remove the const in the params of (2), why is that?
struct widget {
int widget_size;
};
// (1)
// compiler uses this instead of (2)
template <typename Arg>
int get_size(Arg && arg) {
return arg.size;
}
// (2)
int get_size(widget const& arg) {
return arg.widget_size;
}
int main() {
widget w;
get_size(w);
}
答案1
得分: 4
因为编译器忽略了特定的重载。
请注意,版本2更匹配,因为传递的参数缺少const
关键字,版本1也缺少const
关键字。
在这种情况下无法编译。
Widget
类中没有size
成员变量。它有widget_size
,这导致了编译错误。
int get_size(Arg && arg) {
return arg.widget_size; // 看这里
}
如果我在(2)的参数中去掉const,它就能编译,为什么?
这是因为get_size(w);
开始匹配版本2,因此不需要编译器检查版本1中的widget_size
。
英文:
> because the compiler ignored the specific overload .
Please note that Version 2 is a better match as argument passed lacks const
keyword and version 1 also lacks const
keyword.
> that doesn't compile in that case.
Widget
class doesn't have size
member variable in it. It's got widget_size
, which is causing compilation error.
int get_size(Arg && arg) {
return arg.widget_size; // See this
}
> It does compile if I remove the const in the params of (2), why is that?
This is because get_size(w);
started matching version 2, thereby omitting any need for compiler to check for widget_size
in version 1.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论