这是通过 4 层间接发生的事情的精简版本。重叠解析在同名的本地 lambda 附近失效。这是某种维护问题,特别是如果代码仍然可以构建(这里不是)并且错误仅在测试中捕获。
有没有一种优雅的方法来规避这个问题?请参阅Godbolt Playgound对于这个问题。
#include "catch.hpp"
#include <iostream>
#include <map>
#include <string>
namespace {
struct Something {};
template <typename T>
void process(const T& x, Something const& s){}
struct A {
};
void process(A const& p, Something const& s){}
struct B {
};
void process(B const& p, Something const& s){}
} // namespace
int main {
struct C {};
// THIS lanbda shadows the visibility of formerly defined
// functions with same name. This is a maintainability issue
auto process = [](C const& p, Something const& s) {};
Something s{};
A a{};
B b{};
C c{};
process(a, s);
process(b, s);
}
最佳答案
您可能会明确指出过载:
// C++17 implementation, might have similar code for C++11/C++14
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
然后:
auto process = overloaded{
[](C const& p, Something const& s) {},
[](const auto& p, Something const& s){::process(p, s);}
};
关于c++ - 如何避免本地 lambda 影子重载解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49027536/