0

I have some code Similar to this

enum Days
{
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
};

typedef void (*DailyFunction)(int);

namespace DailyFunctions
{
    void monday(int SomeData);
    void tuesday(int SomeData);
    void wednesday(int SomeData);
    void thursday(int SomeData);
    void friday(int SomeData);
    void saturday(int SomeData);
    void sunday(int SomeData);
}

and somewere else in my code I use a switch statement to assign one of the DailyFunctions to a DailyFunction ptr. When i was typing the (more or less) same switch statement for the third time, I had the Idea, that it would be great to have a map

std::map<Days, DailyFunction> MyPhonebookMap

which would allow me to do something like this:

DailyFunction Function_ptr = MyPhonebookMap[WeekDay];

To me it seems, like the optimal place to define such a map would be in the namespace DailyFunctions under the function-declarations

But how can i define a const map there (since it shouldnt change) and populate it at the same time?

Uzaku
  • 511
  • 5
  • 17

2 Answers2

1

You can use boost function boost::assign::map_list_of or use a copy constructor to initialize const map from already constructed map:

#include <map>

int main()
{
    std::map<Days, DailyFunction> m;
    m[ MONDAY] = &monday;
    //... initialize m entries
    std::map<Days, DailyFunction> const mc( m);
    //...
    return 0;
}
4pie0
  • 29,204
  • 9
  • 82
  • 118
0

In your case it is possible to use a simple array instead of the map. You can have an initializer for the const array, plus it will work faster.

    DailyFunction funcs[] = {monday, tuesday, wednesday, thursday, friday, satureday, sunday};

Or, if you use C++11, you can use an initilizer list, like explained here Initializing a static std::map<int, int> in C++

Community
  • 1
  • 1
Andrei Bozantan
  • 3,781
  • 2
  • 30
  • 40
  • Hey, thank you very much for your fast answer. But that is not possbile, because I forgot one important information in my Post. And that is, that the enum doesn't start with 0 and goes to 6 but its more like monday is 7 tuesday is 28 and so on. This may sound very strange but i cannot avoid that. But I will try the Map initialiser u posted. I hope it works with VS 10 :) – Uzaku Apr 22 '14 at 10:19