将成员函数传递给Variadic模板函数

时间:2015-10-30 20:53:12

标签: c++ templates c++11

我有一个名为enqueue的函数的类:

template<class T, class... Args>
inline auto ThreadPool::enqueue(T && t, Args&&... args) ->std::future<typename std::result_of<T(Args ...)>::type>
{
    using return_type = typename std::result_of<T(Args...)>::type;

    auto task = std::make_shared<std::packaged_task<return_type()>> (
       std::bind(std::forward<T>(t), std::forward<Args>(args)...)
    );

    std::future<return_type> result = task->get_future();
    {
        std::unique_lock<std::mutex> lock(m_mutex);

        // Don't allow job creation after stopping pool.
        if (m_done)
            throw std::runtime_error("Enqueue on stopped ThreadPool.");

        m_tasks.emplace([task]() { (*task)(); });
    }

    m_cond.notify_one();
    m_futures.push_back(move(result));
    return result;
}

这是在ThreadPool类旁边的头文件内部完成的内联实现。

它是一个单例,应该能够使用其参数获取任何函数,将其添加到任务队列并返回该函数的结果类型的未来。

以下是我尝试使用它的课程:

void Grepper::scan(std::tr2::sys::path const& folder, std::string expression, bool verbose) {
    // Create directory iterators.
    std::tr2::sys::recursive_directory_iterator d(folder);
    std::tr2::sys::recursive_directory_iterator e;

    // Create tasks from files that match initial extension list.
    for (; d != e; ++d) {
        if (!std::tr2::sys::is_directory(d->status()) && std::find(m_extensions.begin(), m_extensions.end(), d->path().extension().generic_string()) != m_extensions.end()) {
            ThreadPool::get_instance().enqueue(grep, d->path(), expression, verbose);
        }
    }
}

这给出了编译器错误:

Error C3867 'Grepper::grep': non-standard syntax; use '&' to create a pointer to member 

我尝试为此函数创建一个仿函数,并将该函数作为lambda传递:

ThreadPool::get_instance().enqueue([this](std::tr2::sys::path p, std::string s, bool b) { grep(p, s, b); });

这给了我以下编译器错误:

Error C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'

这里的参考是我的grep方法的声明:

void grep(std::tr2::sys::path file, std::string expression, bool verbose);

如何将此函数及其参数正确传递给enqueue方法?

1 个答案:

答案 0 :(得分:2)

The attempt with a pointer to a member function fails for two reasons:

  1. To form a pointer to a member function, you need to use &Grepper::grep syntax.
  2. A member function requires an implicit object parameter (among other arguments, so that it can be also properly handled by std::bind and std::result_of).

Having said that, you could try the following call:

ThreadPool::get_instance().enqueue(
   &Grepper::grep
   , this
   , d->path()
   , expression
   , verbose
);

The attempt with a lambda expression fails, because that lambda expression passed as an argument:

[this] (std::tr2::sys::path p, std::string s, bool b) { grep(p, s, b); }

declares three parameters, so the Args parameter pack must not be empty. But it is in your case:

ThreadPool::get_instance().enqueue(
    [this] (std::tr2::sys::path p, std::string s, bool b) { grep(p, s, b); }        
);

Those arguments, according to your design, should be either passed in a call to enqueue:

ThreadPool::get_instance().enqueue(
    [this] (std::tr2::sys::path p, std::string s, bool b) { grep(p, s, b); }
    , d->path()
    , expression
    , verbose
);

or captured by a lambda expression, so that no additional Args are needed:

ThreadPool::get_instance().enqueue(
    [this,d,expression,verbose] { grep(d->path(), expression, verbose); }
);