jeudi 25 février 2016

passing member tuple to non-member struct without specifying it in template

To avoid XY problem, I have a class with heterogeneous container, basically std::tuple. I want to make the class be able to accept Visitors, applying them to every element of tuple (not really sure if I'm applying it statically). Visitors' visit function will be templatized, so they will be able to fully use specializations of some types.

Problem:

When I want to apply Visitor I need to iterate over a container grabbing information about the Visitor, the tuple, and the index of element that is about to be visited. But when I wanted to create member function, I found that I can't partly specialize it. This is the solution I came up with, but I would like to somehow pass tuple without specifying containing types of tuple in template parameters.

#pragma once
#include <tuple>
#include <functional>

template <typename Visitor, int N, typename ... DataTypes>
struct Extractor
{
    static void applyVisitor(Visitor& v, std::tuple<DataTypes...>& t)
    {
        Extractor<Visitor, N - 1, DataTypes...>::applyVisitor(v, t);
        v.visit(std::get<N>(t));
    }
};

template <typename Visitor, typename ... DataTypes>
struct Extractor <Visitor, 0, DataTypes...>
{
    static void applyVisitor(Visitor& v, std::tuple<DataTypes...>& t)
    {
        v.visit(std::get<0>(t));
    }
};

template <typename ... DataTypes>
class MyTuple
{
    std::tuple<DataTypes...> data;
public:
    MyTuple(std::tuple<DataTypes...> data_) : data(data_) {}

    template <typename Visitor>
    void acceptVisitor(Visitor& v)
    {
        Extractor<Visitor, sizeof...(DataTypes) - 1, DataTypes...>::applyVisitor(v, data);
    }
};

I'm thinking in terms of OOD, so that every function that operate on data of the class should be preferably member function, but seems like C++ templates are from another world. If I'm not doing things right, please suggest another solution.

Aucun commentaire:

Enregistrer un commentaire