gpt4 book ai didi

c++ - 对抽象类的引用不能传递给线程函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:08:03 25 4
gpt4 key购买 nike

<分区>

我想在使用 A 调用的函数中使用对抽象类 ( std::thread ) 的引用作为参数类型.这似乎不可能,因为编译器出于某种原因尝试编译:std::tuple<A> ,即使在我的代码中只有 A 的引用类型用作参数(从不作为值类型)。

#include <cstdlib>
#include <thread>

class A {
public:
virtual void a() = 0;
};

class B : public A {
public:
virtual void a() {
}
};

class C {
public:
C(A& aRef) {
thread = std::thread(&C::doSomething, this, aRef);
}
private:
void doSomething(A& aRef) {

}
std::thread thread;
};

int main(int argc, char* argv[]) {
B b;
C c(b);
return EXIT_SUCCESS;
}

将在 Visual Studio 2017 上输出:

error C2259: 'A': cannot instantiate abstract class
tuple(278): note: see reference to class template instantiation 'std::tuple<A>' being compiled
tuple(278): note: see reference to class template instantiation 'std::tuple<C *,A>' being compiled
thread(49): note: see reference to class template instantiation 'std::tuple<void (__thiscall C::* )(A &),C *,A>' being compiled
main.cpp(18): note: see reference to function template instantiation 'std::thread::thread<void(__thiscall C::* )(A &),C*const ,A&,void>(_Fn &&,C *const &&,A &)' being compiled

为什么 std::thread尝试编译 std::tuple<A> ?如果我调用 C::doSomething直接从主线程,代码编译得很好。

这里有什么我遗漏的吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com