我正在尝试声明一个类“Lambdas”,它将向另一个类“Test”提供 lambdas(及其类型信息)。Lambdas 还持有对具体 Test 实例的“this”引用,以便在 lambdas 内访问 Test 公共成员。我这样做是为了定义 lambdas 一次,然后通过 decltype() 在其他任何地方推断类型但我得到错误:成员访问不完整类型:
template <typename T>
struct LambdasInstances {
T * self;
explicit LambdasInstances(T * p) : self(p) {} // CAPTURE Test "this"
auto genLambda1() {
return [=](int x){
self->testVar; // ERROR: Member access to incomplete type
};
}
};
class Test3 {
public:
LambdasInstances<Test3> instances;
int testVar;
Test3() : instances(this) {}
decltype(instances.genLambda1()) varLambda = instances.genLambda1();
void useLambda() { varLambda(123); }
};
但是如果我要在外部定义 genLambda(),那么我会遇到另一个问题 - 错误:在定义之前不能使用推导类型的 genLambda()!:
template <typename T>
struct LambdasInstances {
T * self;
explicit LambdasInstances(T * p) : self(p) {}
auto genLambda1(); // would be defined after Test3 declaration
};
class Test3 {
public:
int testVar;
LambdasInstances<Test3> instances;
Test3() : instances(this) {}
decltype(instances.genLambda1()) varLambda = instances.genLambda1();
};
// IF WE DEFINE AFTER :: ^ genLambda() with deduced type cannot be used before its defined!
template< typename T>
auto LambdasInstances<T>::genLambda1() {
return [=](int x){
self->testVar;
};
}