如何在C 中提供一个可呼叫的对象访问,例如lambda
How to provide a callable object protected access like lambda in C++?
我有一个lambda,我需要转换为可呼叫的对象,以便我可以专门使用呼叫操作员。我的印象一直是,具有void(auto)
签名的lambda等同于这样的可呼叫结构:
struct callable {
Foo & capture;
template< typename T >
void operator()( T arg ) { /* ... */ }
}
但是,lambda在成员函数中声明时可以访问私人和受保护的成员。
这是一个简化的示例:
#include <iostream>
using namespace std;
class A {
protected:
void a() { cout << "YES" << endl; }
};
class B : public A {
public:
void call1();
void call2();
};
struct callable {
B * mB;
void operator()() {
// This does not compile: 'void A::a()' is protected within this context
// mB->a();
}
};
void B::call1() {
// but then how does this access a() ?!
[&]() { a(); }();
}
void B::call2() {
callable c{ this };
c();
}
int main()
{
B b;
b.call1();
b.call2();
}
是否有任何方法可以在可呼出的结构中模仿这种行为,而无需在标题中宣布它并将其作为朋友类?这似乎是有问题的,因为我会有很多不同的可喊声。我也只是对此感到好奇,因为我的印象是lambdas在功能上与用呼叫操作员声明结构相同。
lambda的访问权限捕获了这一点,似乎说lambda的访问权限与本地班级相同。但是就我而言,我需要效仿通用的lambda,而本地类则不能具有模板成员函数。
您仍然可以捕获this
和&B::a
struct callable {
B* mB;
void (A::*m)();
void operator()() const {
(mB->*m)();
}
};
void B::call2() {
callable c{ this, &B::a };
c();
}
demo
您可以在不提供定义的情况下使struct callable
A的CC_4 A friend
。在遇到真实声明之前,这样的声明甚至没有使名称可见:
class B : public A {
// ...
friend struct callable;
}
// ERROR: callable isn't visible here:
// callable *foo;
如果简短非常重要,则可以将其扩展到大量的朋友中,并以一份声明为例:
class B : public A {
// ...
template<int> friend struct callable;
};
// In implementation:
template<>
struct callable<0> { /* ... */ };
template<>
struct callable<1> { /* ... */ };
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 呼叫获取后,将共享_ptr分配给另一个
- 如果send()返回x字节,则recv()在一个呼叫中获取相同数量的字节
- 流媒体错误:在退出上一个呼叫之前,请再次调用InternetStatusCallback
- 如何在一个呼叫中分配多个变量
- 如何在C 中提供一个可呼叫的对象访问,例如lambda
- 当类层次结构中只有一个类时,请避免在每个功能呼叫上读取V-Table的开销
- 耗尽流程com服务器 - 每个呼叫过程一个服务器进程
- 如何唤醒从另一个线程选择没有超时时间的呼叫
- Qt按钮是呼叫2插槽,我只需要一个