英文:
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<B>(const B&)
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论