Reputation: 958
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);
}
Upvotes: 0
Views: 45
Reputation: 1221
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.
Upvotes: 4