dimanche 11 août 2019

How to tell what types any map consists of

I want to be able to tell if a type in a std::map consists of a std::map itself. My scenario looks like the following:

template <typename Key, typename T, typename Compare = std::less<Key>,
          typename Allocator = std::allocator<std::pair<const Key, T>>>
void mapPrint(std::map<Key, T, Compare, Allocator> m) {
}

How would I check if either Key or T is a std::map? Say I send:

std::map<std::map<int,int>, int> m;

To this function. Is it possible to recursively iterate through all the types until only trivial types are found?

Edit: This is my program:

#include <iostream>
#include <map>

class A {
  public:
    void testFunc(int) {}
};

class B {
  public:
    void testFunc(int) {}
};

class C {
  public:
    void notTestFunc() {}
};

template <typename T>
struct hasTestFunc
{
    typedef char (& yes)[1];
    typedef char (& no)[2];

    template <typename C> static yes comp(decltype(&C::testFunc));
    template <typename> static no comp(...);

    static bool const value = sizeof(comp<T>(0)) == sizeof(yes);
};

template <>
struct hasTestFunc<int> {
    static bool const value = true;
};

template <typename Key, typename T, typename Compare = std::less<Key>,
          typename Allocator = std::allocator<std::pair<const Key, T>>>
void mapPrint(std::map<Key, T, Compare, Allocator> m) {
    std::cout << hasTestFunc<Key>::value << std::endl;
    std::cout << hasTestFunc<T>::value << std::endl;
}

int main() {
  std::map<std::map<A,A>, A> m;
  mapPrint(m);
  return 0;
}

I want the output of this program to be:

0 1 1 1

Right now it is:

0 1

Aucun commentaire:

Enregistrer un commentaire