Reputation: 753
I have a C++ template class that contains a method pointer and a class pointer, and who has single method, call
, that calls the method pointer on the class pointer.
This template is called Method< C >
, C being the class of the class and method pointers.
I want to create an array (std::vector
) of this template, but I want this vector to be able to contain different classes of this template. My final goal is to go through this vector and call the call
method of each of the elements, even if they have different classes.
How would you do that?
Upvotes: 1
Views: 1906
Reputation: 12547
You can not store template
s in vector
, only objects
that have types
. And template
become type
when it is instantiated.
So, you can't do exactly what you want.
I recommend you use function
and bind
. See an example:
struct A
{
void call()
{
std::cout << "hello";
}
};
int main()
{
std::vector <std::function<void()>> v;
v.push_back(std::bind(&A::call, A()));
for (auto it = v.begin(); it != v.end(); ++it) {
(*it)();
}
return 0;
}
It does exactly you want.
Upvotes: 5
Reputation: 3861
If the methods all have the same signature (with respect to the input parameters and return type) then you could wrap them in std::function
objects and store those in the vector. Either way, it sounds like you'll need to wrap your class in some sort of polymorphic type (or derive them from a common, non-templated base -- but then you'll have reinvented std::function
.)
The bottom line here is that std::vector
cannot be made to store heterogeneous types.
Upvotes: 0