jeudi 30 août 2018

C++ Templates access a function with different types

So What I'm trying to do is something like this.

I have a template struct like this one:

template <typename T>
struct TemplateTest
{
    void test(T a)
    {
        switch (typeid(boost::any_cast<T>(a)))
        {
        case typeid(int):
            {
                std::cout << "INT";
                break;
            }
        case typeid(float):
            {
                std::cout << "FLOAT";
                break;
            }
        case typeid(double):
            {
                std::cout << "DOUBLE";
                break;
            }
        default:
            {
                std::cout << "OTHER";
                break;
            };
        }
    }
};

And I want to make a vector with different types of that struct and after just use a for-loop to iterate over all my elements and call this function form all of them.

What I would like to have will be something like this:

typedef boost::variant<TemplateTest<float>(), TemplateTest<double>(), TemplateTest<int>() > variant;
typedef std::vector<variant> TestVar;
TestVar d;
d.push_back(new TemplateTest<float>());
d.push_back(new TemplateTest<double>());
d.push_back(new TemplateTest<int>());
for (auto value : d)
{
    value.test(5);
}

Is out there any way to do this without using a specific cast of my type before my function call?

Aucun commentaire:

Enregistrer un commentaire