Search code examples
c++templatesglobal-variables

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.


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);
    }