重载的模板函数未选择特定类型的正确版本。

huangapple go评论68阅读模式
英文:

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?

godbolt

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&amp; 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?

godbolt

struct widget {
    int widget_size;
};

// (1)
// compiler uses this instead of (2)
template &lt;typename Arg&gt;
int get_size(Arg &amp;&amp; arg) {
   return arg.size;
}

// (2)
int get_size(widget const&amp; 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 &amp;&amp; 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.

huangapple
  • 本文由 发表于 2020年1月4日 12:57:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/59588018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定