aantron / better-enums

C++ compile-time enum to string, iteration, in a single header file
http://aantron.github.io/better-enums
BSD 2-Clause "Simplified" License
1.67k stars 173 forks source link

Support using better-enum as key in dictionaries and maps. #77

Closed svnscha closed 5 years ago

svnscha commented 5 years ago

Thanks for better-enum. It is awesome. However I was missing a feature to use the enum values in _unorderedmap. I have extended it for this use case. Please review and accept my PR.

int main()
{
    Channel channel = Channel::Red;

    std::unordered_map<Channel, int> u = {
        {Channel::Red, 1},
        {Channel::Blue, 3},
    };

    printf("Red %d\n", u[Channel::Red]);
    printf("Blue %d\n", u[Channel::Blue]);

    return 0;
}
svnscha commented 5 years ago

My previous attempt does not work and I totally did not think about that situation that a better enum could be in a namespace. Then the specialization does fail.

However, how about that approach?

namespace test {

BETTER_ENUM(Channel, char, Red = 1, Green, Blue)

}

BETTER_ENUMS_DECLARE_STD_HASH(test::Channel)

int main()
{
    test::Channel channel = test::Channel::Red;

    std::unordered_map<test::Channel, int> u = {
        {test::Channel::Red, 1},
        {test::Channel::Blue, 3},
    };

    printf("Red %d\n", u[test::Channel::Red]);
    printf("Blue %d\n", u[test::Channel::Blue]);

    return 0;
}
aantron commented 5 years ago

However, how about that approach?

If it works, I will merge it :)

If possible, can you add a test case that exercises this? It should probably go somewhere in this block:

https://github.com/aantron/better-enums/blob/8a0d376b5343986970ded91d08489597ddc05ddb/test/cxxtest/general.h#L30-L32

svnscha commented 5 years ago

However, how about that approach?

If it works, I will merge it :)

If possible, can you add a test case that exercises this? It should probably go somewhere in this block:

https://github.com/aantron/better-enums/blob/8a0d376b5343986970ded91d08489597ddc05ddb/test/cxxtest/general.h#L30-L32

Do you mean by making a test case that tests the unordered_map?

aantron commented 5 years ago

Do you mean by making a test case that tests the unordered_map?

Yes.

svnscha commented 5 years ago

I am going to add the test case on Monday.

svnscha commented 5 years ago

I have added a new runtime test @aantron as I dont know if it is really possible to make a std::hash operator usable in a constexpr. Would you chheck it out and see if that is how you wanted it?

aantron commented 5 years ago

A run-time test is fine. It looks like it's not compiling, though. See, e.g., https://travis-ci.org/aantron/better-enums/jobs/558780607#L1386.

svnscha commented 5 years ago

Wow, finally.. @aantron ^^

aantron commented 5 years ago

:p

Thanks!