semtexzv semtexzv - 2 months ago 14
C++ Question

Variadic template class - variadic member function

I am working on project that requires generic cache for multiple stored classes. My base class looks like this:

template<typename ... Types>
class VarCache{
template<typename T>
using item_type = shared_ptr<holder<T>>;
template<typename T>
using map_type = map<int64_t,item_type <T>>;
public:
std::tuple<map_type<Types>...> caches;
};


I need to write function that would accept no arguments, but by calling it on cache object, it would iteratively traverse all stored map variants, and perfrom action(removing unneeded items).

Example:

I have
VarCache<A,B,C> cache
and method
prune<T>();
where
T
is one of
A,B,C


and by calling
cache.prune_all_variants();
I want cache to perform

prune<A>();
prune<B>();
prune<C>();


is this possible ?

Answer

There are a few tricks you can use to call a function for each element of a parameter pack. Here's one option:

void prune_all_variants() {
    (void)std::initializer_list<int> {
        (prune<Types>(), 0)...  
    };
}

In C++17, this can be simplified to the following using fold expressions:

void prune_all_variants() {
    (prune<Types>(), ...);
}