在不知道其声明签名的情况下将任意函数对象存储到类成员容器中 [英] Storing arbitrary function objects into a class member container without knowing their declaration signature
问题描述
我有一个类模板,我不知道是否需要将 class Func
作为其参数之一。我也不知道是否可以将 std :: function
直接存储到没有模板参数列表的容器中。我的班级看起来像这样:
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;
};
当我去编写将添加数据,线程和函数对象的函数时,类似{ code>函数对象,函数指针
, lambda
, std :: function< ...>
}是否可以类似地声明 function
的参数?
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;
如果第二种情况是首选方式,那么我将如何实际存储 func obj
?是首选 std :: forward
还是 std :: move
?添加对象的方法是否应声明为 Func&& func
?
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
?
我想尽可能保持此类的通用性,模块化和可移植性,同时努力保持最佳的现代c ++ 17
I'd like to keep this class as generic, modular and portable as possible while trying to maintain modern c++17 best practices.
编辑
在听完用户Liliscent的建议后,我认为这就是她在整个评论中所说的。
After listening to user Liliscent's advice I think this is what she was stating throughout the comments.
std::vector<std::function<Func>> _storedFuncObjs;
推荐答案
为什么该类存储 std :: thread
s 和 数据
s 和 Func
s?
Why is this class storing std::thread
s and Data
s and Func
s?
这些线程的可调用对象是什么?
What Callable are you starting those threads with?
-
Func
的实例已应用于Data
?
- 您只需要
线程
s。
- Instances of
Func
applied toData
?- You only need the
thread
s.
- 存储
std :: future< Data>
s(可能还有thread
,具体取决于您如何创建期货)
- Store
std::future<Data>
s (and possiblythread
s, depending on how you create the futures)
- 存储
std :: packaged_task< Data(Args ...)>
并分发std :: future< Data>
是创建的那些。
- Store
std::packaged_task<Data(Args...)>
and hand out thestd::future<Data>
s those created.
这篇关于在不知道其声明签名的情况下将任意函数对象存储到类成员容器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- You only need the
- 您只需要