0

I have several collections of different types of objects and various types of containers in C++. I need to perform some common operations in this collections, for instance, clean and resize the containers. Is there a way to do it writing a short code? For example, consider the following code:

#include <vector>
#include <unordered_map>

using namespace std;

class A {};
class B {};
class C {};

int main() {
    vector<A> a;
    vector<B> b;
    vector<C> c;
    unordered_map<int, int> map;

    // I would like something like this...
    for(auto& ct : {a, b, c, map}) {
        ct.clear();
        ct.reserve(1000);
    }

    return 0;
}

Of course, the code above is invalid on C++11, since the compiler cannot deduce the list. I have more or less ten containers but these number can go up. So, the code must be equivalent (in size) to apply the operations to these containers separately.

Thanks very much for your help.

an_drade
  • 664
  • 1
  • 5
  • 15
  • 2
    Look at [how-to-iterate-over-a-tuple-in-c-11](http://stackoverflow.com/questions/26902633/how-to-iterate-over-a-tuple-in-c-11) – Jarod42 Feb 09 '16 at 17:41

2 Answers2

2

You could implement a function likeapply whose first argument takes a generic operation (such a generic lambda), and the rest of the arguments are objects on which you want to apply the operation:

apply
(
   [](auto && c) { c.clear(); c.reserve(100); },  //use: -std=c++14
   a,
   b,
   c,
   map
);

Here is one possible implementation:

template<typename Op, typename ... Cs>
void apply(Op op, Cs && ... args)
{
   using unpack = int[];
   unpack {0, ( op(std::forward<Cs>(args)), void(), 0 ) ... };
}

Hope that helps.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

Boost any may be useful in this case: http://www.boost.org/doc/libs/1_60_0/doc/html/any/s02.html

phg1024
  • 169
  • 6