mercredi 29 septembre 2021

How to use dynamic_pointer_cast with variadic templates?

My goal is to have a function (foo) which takes an arbitrary number of types (...TArgs), and tries to cast some shared pointers (myInt, myDouble and myChar (see below)) to the given corresponding shared pointer types (shared_ptr<TArgs...>). If the cast is successful it should do some stuff, otherwise just continue running.

I tried to achieve this with using dynamic_pointer_cast on variadic template arguments. However, the concept of variadic templates and how to use them is fairly new to me. I tried to use variations of the below code but none of them worked. Could you please help me out how can I create a function?

// Example program
#include <iostream>
#include <memory>

template <typename T>
struct Base {
    Base(T data) : _data(data){}
    T get() const {return _data;}
protected:
    T _data;
};

struct Int : Base<int>{
    Int(int data) : Base(data){}
};
struct Double : Base<double>{
    Double(double data) : Base(data){}
};
struct Char : Base<char>{
    Char(char data) : Base(data){}
};


template <typename ...TArgs>
void foo()
{
    const auto myInt = std::make_shared<Int>(1);
    const auto myDouble = std::make_shared<Double>(3.14);
    const auto myChar = std::make_shared<Char>('a');
    
    if (const auto x = std::dynamic_pointer_cast<TArgs>(myInt)...) // syntax error
    {
        std::cout << "casted myInt with value = " << x->get() << "\n";
    }
    if (const auto x = std::dynamic_pointer_cast<TArgs>(myDouble)...) // syntax error
    {
        std::cout << "casted myDouble with value = " << x->get() << "\n";
    }
    if (const auto x = std::dynamic_pointer_cast<TArgs>(myChar)...) // syntax error
    {
        std::cout << "casted myChar with value = " << x->get() << "\n";
    }
}

int main()
{
    foo<Int, Char>();
    return 0;
}

Expected output of above code:

casted myInt with value = 1
casted myChar with value = a

Aucun commentaire:

Enregistrer un commentaire