按条件切换命名空间

时间:2011-01-17 14:57:44

标签: c++ namespaces if-statement

在我的C ++程序中,我有几个名称空间包含几个名称相同的指针。 然后我想要一个函数根据参数选择命名空间。即类似的东西:

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

但是,这不起作用,因为编译器抱怨在该范围内不知道x。我想问题是“使用命名空间......”仅在if语句中有效。 我认为应该可以以某种方式切换命名空间,但无法找出如何... 你知道怎么做而不单独铸造所有变量吗?

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

干杯, 帕斯卡

7 个答案:

答案 0 :(得分:4)

命名空间是C ++中的编译时功能,您无法在运行时动态操作它们。我能给你的最好的建议就是尝试不同的方法 - 命名空间可能并不意味着你想做什么。所以问问你 想要做什么,你可能会在不弯曲系统的情况下得到一个好的答案。

答案 1 :(得分:1)

命名空间在编译时使用。 if状态是在运行时执行的。

您无法在运行时切换编译器行为。

答案 2 :(得分:1)

我不明白为什么你不想要这个:

double* dispatch(int b)
{
    switch(b)
    {
        case 1: return ns1::x;
        case 2: return ns2::x;
        default: return 0;
    }
}

int main()
{
    int b=1;
    std::cout << dispatch(b)[3] << std::endl;
}

如果这种情况会增长,请考虑使用类和多态而不是命名空间。

答案 3 :(得分:1)

在最简单的状态下,您有“静态”数据,但想要决定使用哪一块静态数据。

struct space
{
  double x[5];
};

space space1 = space{ {1,2,3,4,5} };
space space2 = space{ {6,7,8,9,10} };

int main( int argc, char * argv[] )
{
   space * s;
   if( argc == 1 )
       s = &space1;
   else
       s = &space2;
}

实际上,您的空间当然不仅仅是一个成员,您将以不同的方式填充它们,但这是您可以选择使用哪个实例的一种方式。

您可以使用多态来实现函数,但这很大程度上取决于您需要它。

答案 4 :(得分:0)

我不相信命名空间是在运行时确定的东西...因此你将无法设置它。

快速谷歌“在运行时更改命名空间”返回http://www.velocityreviews.com/forums/t288720-changing-namespace-at-runtime.html

希望有所帮助。

答案 5 :(得分:0)

using namespace指令基本上告诉编译器“在解析符号时尝试使用它”,这在运行时不会发生。

我认为第二种方法没有任何问题......

答案 6 :(得分:0)

如前所述,它不起作用......如果你想在容器类中放入许多变量来实现预期的结果,我建议你使用多态:

// Header file
class s
{
  public:
    double x[5];
}

class s1: public s 
{
  public:
    s1() { /* Assign x here */ };        
}

class s2: public s
{
  public:
    s2() { /* Assign x here */ };
}

// CPP file
int main()
{
  int b = 1;
  s* sptr;

  if (b == 1)
    sptr = (s*)new s1();
  else
    sptr = (s*)new s2();

  std::cout << sptr->x[3] << std::endl;
  delete sptr;
} 

如果你只有一些变量,你可以使用指针。

int main()
{
  int b = 1;
  double *px;
  double s1x = {1, 2, 3, 4, 5};
  double s2x = {6, 7, 8, 9, 10};

  if (b == 1)
    px = &s1x;
  else
    px = &s2x;

  std::cout << px[3] << std::endl;
}