【发布时间】:2023-03-16 07:40:01
【问题描述】:
我正在尝试模仿 std::thread 构造函数功能:
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
我尝试使用调试器单步执行以查看它是如何工作的,但我无法弄清楚。
如何像线程的构造函数一样创建和存储绑定类型?
类似这样的东西(语法可能错误):
class myClass{
private:
auto bindType;
public:
template< class Function, class... Args >
explicit myClass( Function&& f, Args&&... args ) : bindType(somehowBind(f, args) {}
void evaluate() {bindType();}
};
使用示例:
int test(int i) {return i;}
int main(){
myClass my(test, 5);
my.evaluate();
}
请注意,我不在乎 somehowBind 函数是否会忽略返回类型,即它的返回类型可以是 std::function 之类的东西。
我不想做的就是了解如何将class... Args 绑定到给定的函数f,这样在调用somehowBind 之后它就会像std::bind 那样工作。
为了澄清我的观点,您可以考虑一下我想要达到的目标:
thread t(test, 5); // unlike the usual std:::thread, this one is created in suspended mode therefore I need somehow to bind `f` with `5` and store it
t.start(); // now t is executed
这有点像 C# 和 Java 线程,它们不是在构造后立即执行的。
【问题讨论】:
-
我认为您需要多解释一下您想要实现的目标。
-
在包装代码层的深处会有一个
std::tuple存储可变参数、指针或对它们的引用。正如 Tomasz 所说,请详细说明您的包装代码应该是什么样的。 -
您在寻找
std::function吗?class myClass { std::function<void()> m; public: template<class F, class... Args> myClass(F&& f, Args&&... args) : m(std::bind(std::forward<F>(f), std::forward<Args>(args)...)) {} void evaluate() {m();} }; -
@dyp 是的,我正在寻找的那个,我不知道您可以将这样的语法与 std::bind 一起使用(转发 ... 绑定)。我不知道为什么,但在 std::thread 中,它们太复杂了。
-
@dyp 得到的
std::bind表达式函子的返回值可能不是void。