switch namespace by if condtion

Posted by pascal on Stack Overflow See other posts from Stack Overflow or by pascal
Published on 2011-01-17T14:57:43Z Indexed on 2011/01/17 15:53 UTC
Read the original article Hit count: 176

Filed under:
|
|

Hi,

in my C++ program I have several namespaces that contain several pointers with identical names. I then want a function to choose a namespace according to a parameter. I.e. something like:

#include <iostream>

namespace ns1{
double x[5]={1,2,3,4,5};
}
namespace ns2{
double x[5]={6,7,8,9,10};
}

int main(){
  int b=1;
  if(b==1){
    using namespace ns1;
  }
  if(b==2){
    using namespace ns2;
  }
  std::cout << x[3] << std::endl;
}

However, this doesn't work since the compiler complains that x isn't known in that scope. I guess the problem is that "using namespace ..." is only valid within the if-statement. I think that it should be possible to switch namespaces somehow, but cannot find out how... Do you know how to do this without casting all variable separately?

int main(){
  int b=1;
  double *x;
  if(b==1){
    x = ns1::x;
  }
  if(b==2){
    x = ns2::x;
  }
  std::cout << x[3] << std::endl;
}

Cheers, Pascal

© Stack Overflow or respective owner

Related posts about c++

Related posts about namespaces