4

Is there an alternative to boost-hana in boost library which will allow me to create something like

typedef boost::AlterinativeToHana::map< make_pair<"abcd",ABCDType>,
                 make_pair<"efgh",EFGHType>,
                 make_pair<"ijkl",IJKLType>
               > stringToTypeMap;

I have used boost-fusion, but I could not find a proper solution for my use case i.e character string to type mapping.

cpplearner
  • 13,776
  • 2
  • 47
  • 72
Recker
  • 1,915
  • 25
  • 55
  • 1
    Out of curiosity, why do you need an alternative to Hana? – Louis Dionne Jun 05 '16 at 15:11
  • @LouisDionne... My workplace's platform compilers are still using Boost 1.56 and dont plan to upgrade it till early 2018. – Recker Jun 05 '16 at 16:11
  • Ah, ok. If you are using a modern compiler (probably not the case if you use the platform's compiler), however, you can also install Hana only without having to update your Boost distribution. – Louis Dionne Jun 05 '16 at 20:14
  • @LouisDionne... Ahh, I think I created some confusion there. When I said platform, I meant OS's (`Win, OS-X and Linux`) all the modern 64 bit compilers. For Linux/OS-X we compile with `--std=c++11` switch and we dont plan to upgrade it to use C++14 any-time soon. So even if I do decide to use Hana, I might not be able to use its full functionality as the compiler requirements for Hana suggest that it needs C++14 compilers. – Recker Jun 06 '16 at 03:04
  • 1
    Ok. Hana will definitely not work without -std=c++14. – Louis Dionne Jun 06 '16 at 16:45
  • Are you trying to map run-time string values to types or will the string values always be known at compile-time? – Jason Rice Jun 23 '16 at 22:24
  • Strings will be known at compile time. – Recker Jun 24 '16 at 06:19

1 Answers1

6

I think std::type_index is what you need:

#include <iostream>
#include <typeindex>
#include <map>

class A
{};

class B
{};

int main()
{   
    std::map<std::type_index, std::string> typesMap;
    typesMap[typeid(A)] = "1111";
    typesMap[typeid(B)] = "2222";

    A instA;
    B instB;

    cout << "instA: " << typesMap[typeid(instA)] << "\n";
    cout << "instB: " << typesMap[typeid(instB)] << "\n";

    return 0;
}

Output:

instA: 1111
instB: 2222
Dmitriy Zapevalov
  • 1,357
  • 8
  • 13
  • 4
    I actually needed the reverse mapping here as opposed to what you have mentioned. From `std::string` to a well defined type. – Recker Jun 05 '16 at 12:21
  • As you understand it is no problem to make `std::map`. I made this `type->string` mapping because this example is easier to understand. In real life you will need something more conneted with `std::type_info` like `construction functions`. – Dmitriy Zapevalov Jun 05 '16 at 12:27