Search code examples
c++c++11templatesc++14variadic-templates

Make decision depending on variadic types


I know I have made the title as blurry as possible, but the sample will hopefully set the goals.

I have a Base class and families of Derived classes (classy OOD, nothing more).
Furthermore I have a function which takes variadic templates and I want to make decision depending on those templates.

template<typename... Ts>
void do_smth(std::vector<std::shared_ptr<Base>>& vec) {
    for (auto&& ptr: vec) {
        if the dynamic type of ptr is one of Ts.. then do smth.
    }
}

And I intend to call the function as this:

do_smth<Derived1, Derived2>(vec);

I know I could forward the Ts... to std::variant check with hold_alternative or smth like this, but I have only types not values. And to complicate the matters, my compiler is limitied with C++14 support.
Can someone please suggest some tiny/elegant solution to this?


Solution

  • And to complicate the matters, my compiler is limited with C++14 support.

    C++14 ... so you have to simulate template folding...

    What about something as follows?

    template<typename... Ts>
    void do_smth (std::vector<std::shared_ptr<Base>>& vec) {
    
        using unused = bool[];
    
        for ( auto&& ptr: vec)
         {
           bool b { false };
    
           (void)unused { b, (b = b || (dynamic_cast<Ts*>(ptr) != nullptr))... };
    
           if ( b )
            { 
              // ptr is in Ts... list
            }
           else
            { 
              // ptr isn't in Ts... list
            }
        }
    }