Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ template for global variable names

I would like to have a function template in C++, that is able to use global variable names as template arguments. Something like this (the presented code is useless but I am interested into the concept):

int v1,v2;

template <int variable>
void run(int offset)
{
  variable = variable + offset;
}

main()
{
  v1 = v2 = 0;
  run<v1>(4);
  run<v2>(8);
}

If template is not the correct mechanism, what else would be better? My problem is, that now I have ten copies of the same (very long) function run() that differ only in the name of used global variables.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use regular function arguments instead:

void run(int& variable, int offset);

int main()
{
  int v1 = 0, v2 = 0;
  run(v1, 4);
  run(v2, 8);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading