Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro to repeat almost the same code

I have to write same code dependent on compile time constant parameter, something like:

map["text 0"] = vec[0];
map["text 1"] = vec[1];
...
map["text n"] = vec[n];

The problem is that I don't know n when I'm writing the code, I receive it as template parameter. The obvious solution is to use one loop and generate the "text k" inside the loop and use vec[k], but this has runtime overhead when it should be done at compile time. Another solution would be to specialize the function for different N values, but in this way I'll have to write same code by hand multiple times and there is no reason to make it template.

I know there are some smart macros that can repeat similar things N times(like BOOST_PP_REPEAT macro family), but I can't find one solution for my specific problem.

Do you have any solution for this problem?

like image 303
Mircea Ispas Avatar asked Oct 05 '22 14:10

Mircea Ispas


1 Answers

Unless you have really, really tight performance constraints, there is no reason to worry about the run-time overhead. Insertions are going to be performed at run-time anyway, and insertion time is definitely going to dominate the time required to change a character in a string.

Moreover, macros are hard to debug and to maintain: avoid them if possible. Here, I would suggest to unroll a simple loop:

std::string s = "text 0";
std::map<std::string, int> m;
for (int i = 0; i < N; i++)
{
    m[s] = vec[i];
    s[5] = '1' + i; // This is going to be the run-time overhead...
}

If your numbers grow higher than 9, in C++11 you could use the to_string() function for converting an integer into a string:

std::string const s = "text ";
std::map<std::string, int> m;
for (int i = 0; i < N; i++)
{
    m[s + std::to_string(i)] = vec[i];
}

If performance will prove to be an issue, then you can try a more hardcore approach based on macros. However, if your measurements won't indicate a significant overhead, prefer simplicity and clarity and unroll a simple loop.

like image 79
Andy Prowl Avatar answered Oct 13 '22 10:10

Andy Prowl