如何将可变参数模板参数绑定到函数

Job*_*ick 4 c++ c++11

我正在尝试模仿 std::thread 构造函数功能:

template< class Function, class... Args > 
explicit thread( Function&& f, Args&&... args );
Run Code Online (Sandbox Code Playgroud)

我试过使用调试器来查看它是如何工作的,但我无法弄清楚。

如何像线程的构造函数那样创建和存储绑定类型?

像这样(语法可能错误):

class myClass{
private:
auto bindType;

public:
template< class Function, class... Args > 
explicit myClass( Function&& f, Args&&... args ) : bindType(somehowBind(f, args) {}
void evaluate() {bindType();}
};
Run Code Online (Sandbox Code Playgroud)

用法示例:

int test(int i) {return i;}

int main(){
myClass my(test, 5);
my.evaluate();
}
Run Code Online (Sandbox Code Playgroud)

请注意,我不在乎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
Run Code Online (Sandbox Code Playgroud)

这有点提醒 C# 和 Java 线程,它们在构造后不会立即执行。

Snp*_*nps 5

对于初学者来说,使用简单的方法将一些参数绑定到一个函数std::bind

// Some function.
void printValues(int x, double y) {
    std::cout << x << " " << y << std::endl;
}

auto func = std::bind(printValues, 5, 2.0); // Bind params and return functor.
func(); // Evaluate function call (returns void in this case).
Run Code Online (Sandbox Code Playgroud)

接下来,要将函子及其参数存储在一个类中并且您在评估时不关心返回值,那么只需使用 lambda 表达式来包装std::bind表达式(lambda 用于删除返回值):

struct Foo {
    template <typename Function, typename... Args>
    Foo(Function&& func, Args&&... args) {
        auto f = std::bind(std::forward<Function>(func), std::forward<Args>(args)...);
        func_ = [f] { f(); };
        // func_ = [f{std::move(f)}] { f(); }; // In C++14 you can move capture.
    }
    void evaluate() { func_(); }
    std::function<void()> func_;
};
Run Code Online (Sandbox Code Playgroud)

另请参阅此实时示例

如果您要存储可变参数包,请参阅此答案:如何存储可变参数模板参数?