2

I would like to know the best way or better ways of doing something like this:

template <int N,typename T,typename X>
class MyMap : public map<T,MyMap<N-1,T,X>>{};

template <typename T,typename X>
class MyMap<1,T,X> : public map<T,X>{};

int main(int argc, char* argv[])
{
    MyMap<4,string,double> myMap;

    myMap["a"]["b"]["c"]["d"] = 123.456;

    cout << myMap["a"]["b"]["c"]["d"];

    return 0;
}
4

2 回答 2

6

You should use a typedef, not inheritance, and give the parameters more meaningful names and that kind of thing so that it's more readable.

template<int N, typename Key, typename Value> struct map {
    typedef std::map<Key, typename Map<N - 1, Key, Value>::type> type;
};
template<typename Key, typename Value> struct map<1, Key, Value> {
    typedef std::map<Key, Value> type;
};
int main() {
    map<4, string, double>::type lolsmap;
}
于 2011-05-20T00:52:22.953 回答
4

Do not inherit. Use a class to create the type with metaprogramming, then use it. I've compiled this code and it should work:

#include <map>
#include <iostream>

template <int N, typename T, typename X>
class MyMapCreator {
   public:
    typedef ::std::map<T, typename MyMapCreator<N - 1, T, X>::type> type;
};

template <typename T, typename X>
class MyMapCreator<1, T, X> {
   public:
    typedef ::std::map<T, X> type;
};

int main(int argc, char *argv[])
{
    using ::std::cout;

    MyMapCreator<4, ::std::string, double>::type myMap;

    myMap["a"]["b"]["c"]["d"] = 123.456;

    cout << myMap["a"]["b"]["c"]["d"];

    return 0;
}
于 2011-05-20T00:48:21.177 回答