vendredi 23 juin 2017

Template class accepting std::vector

I'm trying to write a templated getter function, that excepts std::array and also std::vector with arbitrary content of type T and returning one value of it

Map2d.h

#include <vector>
#include <array>

class Map2d {
    private:
    unsigned int m_width;
    unsigned int m_height;
    unsigned int m_size;

    public:
    Map2d(unsigned int width, unsigned int height)
        : m_width(width), m_height(height) {
        m_size = m_width * m_height;
    }

    template <typename T>
    struct is_array_or_vector {
        enum { value = false };
    };

    template <typename T, typename A>
    struct is_array_or_vector<std::vector<T, A>> {
        enum { value = true };
    };

    template <typename T, std::size_t N>
    struct is_array_or_vector<std::array<T, N>> {
        enum { value = true };
    };

    template <typename V, template <typename, typename...> class T, typename... Args>
    typename std::enable_if<is_array_or_vector<T<V, Args...>>::value, V>::type
    get(const T<V, Args...>& con, const unsigned int x, const unsigned int y) {
        assert(con.size() <= m_size);
        return con[m_width * y + x];
    }
};

Main.cpp

#include "Map2d.h"
int main() {
    Map2d map(10, 10);

    std::vector<int> v(100);
    std::cout << map.get(v, 5, 5) << std::endl; // works

    std::array<int, 100> a;
    std::cout << map.get(a, 5, 5) << std::endl; // not working

    std::list<int> l(100);
    std::cout << map.get(l, 5, 5) << std::endl; // should not work
    return 1;
}

What do I need to change to get this working? My version is compareable to this answer, with the difference, that the return value is void and not flexible.

I am thankful for every hint! :)

Aucun commentaire:

Enregistrer un commentaire