c++ - 如何将可变参数模板参数绑定(bind)到函数

标签 c++ c++11

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

template< class Function, class... Args > 
explicit thread( Function&& f, Args&&... args );

我试过使用调试器单步执行以查看它是如何工作的,但我无法弄明白。

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

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

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 绑定(bind)到给定函数 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::bind 将一些参数绑定(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).

接下来,要将仿函数及其参数存储在一个类中并且在求值时不关心返回值,则只需使用 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_;
};

Also see this live example

如果您要存储可变参数包,请查看此答案:How to store variadic template arguments?

关于c++ - 如何将可变参数模板参数绑定(bind)到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21349339/

相关文章:

c++ - windows 7和msvc下编译QT 5.3.2

c++ - 分配给匿名实例的基本类型的默认构造函数

c++ - range-for 循环到底做了什么?

c++ - 传递 unique_ptr 右值引用结果编译错误

c++ - 在单词词典中获取以片段开头/包含/结尾的单词

c++ - 如何使用 Boost.Sort string_sort 函数使 C++ 结构快速运行

java - Linux 上 64 位架构的 JNI 库名称

c++ - void init(Handle<Object> exports) 中的 <Object> 是什么

c++ - 自定义分配器编译困难

c++ - 这个怎么自动完成?