Storing arbitrary function objects into a class me

2019-07-27 05:06发布

I have a class template, and I do not know if I need to have as one of its arguments class Func or not. I also do not know if I can arbitrarily store a std::function directly into a container without its template argument parameter list. My class looks something like:

template<class Data, class Func>
class ThreadManager final {
private:
    std::vector<std::shared_ptr<Data>> storedDataPtrs;
    std::vector<std::shared_ptr<std::thread>> storedThreadPtrs;

    // Is this valid? I know that `std::function is a class template wrapper 
    // that depends on template argument types. However I do not know
    // what kind of func will be stored...
    std::vector<std::shared_ptr<std::function>> storedFunctionPtrs;

public:
    ThreadManager() = default;
    ~ThreadManager() = default; // will change to clean up containers.
    ThreadManager( const ThreadManager & c ) = delete;
    ThreadManager& operator=( const ThreadManager & c ) = delete;        
};

Also similar when I go to write the function that will add the data, thread and function object {function object, function pointer, lambda, std::function<...>} Would I be able to declare the parameter for the function similarly?

Or should I just use the actual template argument itself?

 std::vector<std::shared_ptr<Func>> storedFuncPtrs;

And if the second case here is the preferred way, then how would I go about to actually store the func obj? Would std::forward or std::move be preferred? Should the method to add in the objects be declared as Func&& func?

I'd like to keep this class as generic, modular and portable as possible while trying to maintain modern c++17 best practices.


Edit

After listening to user Liliscent's advice I think this is what she was stating throughout the comments.

std::vector<std::function<Func>>  _storedFuncObjs;

1条回答
Luminary・发光体
2楼-- · 2019-07-27 05:24

Why is this class storing std::threads and Datas and Funcs?

What Callable are you starting those threads with?

  • Instances of Func applied to Data?
    • You only need the threads.
  • Instances of Func applied to passed arguments, such that a Data is produced?
    • Store std::future<Data>s (and possibly threads, depending on how you create the futures)
  • Instances of Func that you will call at some future point?
    • Store std::packaged_task<Data(Args...)> and hand out the std::future<Data>s those created.
查看更多
登录 后发表回答