如何解决为什么在从 C++ 中的 lambda 类型继承时需要类内使用声明?
我想制作一个实用程序,允许将多个 lambda 组合成一个重载的函子。在 C++17 中它实际上很简单,只有大约 5 行代码:
template <typename... Funcs>
struct overload : public Funcs... {
using Funcs::operator()...;
constexpr overload(Funcs&&... funcs) noexcept : Funcs{funcs}... {}
};
我想知道为什么需要使用声明?最初,当我写这篇文章时,我没有包含 using Funcs::operator()...;
行,编译器 (GCC) 抱怨 operator()()
不明确。
为什么这里需要使用声明?据我所知,类内使用声明用于在派生类中创建基类 protected
的 public
成员。由于 lambda 类型已经将 operator()()
声明为 public
,因此 using 声明应该没有区别。
Here is an example usage code (godbolt):
auto f = overload{
[](int){return "int ";},[](char){return "char ";},[](float){return "float ";},[](){return "void ";}
};
std::cout << f(3) << f('a') << f();
解决方法
呼叫操作员有一个名字。它的名字是operator()
。在考虑派生类的接口时,派生的 operator()
名称是名称查找的唯一候选。
每个基类的 operator()
必须导入到派生类的命名空间中,否则它不是名称查找的候选对象。
和这个一样:
struct base
{
void foo();
};
struct derived : base
{
// uncomment next line to allow this to compile
// using base::foo;
void foo(int);
};
void test(derived& d)
{
// matches the signature of the base class's foo(),// not the derived classes foo(int)
d.foo();
}
在上面的声明中,derived::foo
隐藏了不可用的 base::foo
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。