考虑到这个众所周知的 C++ 模式:
template <class... Ts> struct overload : Ts... { using Ts::operator()...; };
template <class... Ts> overload(Ts...) -> overload<Ts...>; // clang needs this deduction guide,
// even in C++20 for some reasons ...
不知道为什么将参数之一声明为可变 lambda 会更改覆盖分辨率。实例here on godbolt :
#include <iostream>
template <class... Ts> struct overload : Ts... { using Ts::operator()...; };
template <class... Ts> overload(Ts...) -> overload<Ts...>; // clang needs this deduction guide,
// even in C++20 for some reasons ...
auto main() -> int
{
auto functor_1 = overload{
[](int &&){
std::cout << "int\n";
},
[](auto &&) { // making this lambda `mutable` makes deduction mismatch ?
std::cout << "smthg else\n";
}
};
functor_1(42); // prints `int`
auto functor_2 = overload{
[](int &&){
std::cout << "int\n";
},
[](auto &&) mutable {
std::cout << "smthg else\n";
}
};
functor_2(42); // prints `smth else`
}
最佳答案
和
auto functor = overload{
[](int &&){
std::cout << "int\n";
},
[](auto &&) {
std::cout << "smthg else\n";
}
};
functor(42); // prints `int`
两个闭包都有const
合格 operator()
就是这样 int&&
是更好的匹配,因为它不是模板。和
auto functor = overload{
[](int &&){
std::cout << "int\n";
},
[](auto &&) mutable {
std::cout << "smthg else\n";
}
};
functor(42); // prints `smthg else`
您的 auto&&
关闭不是const
不再合格,意味着没有 const
为了调用它需要发生的资格调整。这使得重载成为身份完全匹配,而 int&&
过载需要 const
资格调整。身份完全匹配胜过const
资格调整精确匹配每[tab:over.ics.scs]所以这就是为什么你会看到 auto&&
版本称为。
关于C++ 重载模式 : call resolution with mutable lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66890356/