Function Overloading failed

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

Function Overloading failed

问题

当比较两种方法时,如果一种方法仅基于方法的签名比另一种方法匹配得更好,但在推断之后该更好的匹配方法失败,为什么编译器直接报告错误?而且似乎不符合SFINAE。

编译器显示错误:对于该代码,“const class B”没有名为“doSomething”的成员。

英文:

When comparing two methods, if one method has a better match than the other solely based on the method's signature. And that better match ,method fails after deduction, why does the compiler directly report an error? And it seems not comply with the SFINAE.

#include <iostream>

class B {};

template <typename T>
void func(const T& t) {
    t.doSomething();
    std::cout << "func(T) - T does not have a member function 'doSomething()'" << std::endl;
}

template <typename T>
void func(T&& t)  {
    std::cout << "func(T) - T has a member function 'doSomething()'" << std::endl;
}



int main() {
    const B b{};
    func(b);  

    return 0;
}

The compiler shows error: ‘const class B’ has no member named ‘doSomething’ for the code

答案1

得分: 2

函数的定义对SFINAE和重载分辨没有影响。

重载分辨:

func(b);将始终调用func<B>(const B&),因为它是更好的匹配项。详细信息请参见https://en.cppreference.com/w/cpp/language/overload_resolution。

SFINAE:

在您的代码中没有SFINAE。有基于返回类型的SFINAE,基于参数类型的SFINAE,可能还有其他类型的SFINAE,但没有基于函数模板实现的SFINAE。

调用函数:

一旦重载分辨确定了调用哪个函数,调用t.doSomething();会导致硬错误,因为B没有这样的方法。

英文:

The definition of the function has no impact on SFINAE nor on overload resolution.

Overload resolution:

func(b); will always call func&lt;B&gt;(const B&amp;) because its the better match. For details see https://en.cppreference.com/w/cpp/language/overload_resolution.

SFINAE:

There is no SFINAE in your code. There is return-type based SFINAE, parameter type based SFINAE, and maybe more, but no SFINAE based on a function templates implementation.

Calling the function:

Once overload resolution decided what function is called calling t.doSomething(); is a hard error because B has no such method.

huangapple
  • 本文由 发表于 2023年6月13日 16:43:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76463136.html
匿名

发表评论

匿名网友

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

确定