if 语句中的几个别名命名空间

Jus*_*ock 5 c++ namespaces

是否可以在 if 语句中设置名称空间别名并在之后使用它?

我用下面的代码尝试过:

 const int dim = 2;
         //default namespace
        namespace poissonProblem = poissonProblem3D;
         //trying to set the necessary namespace
        if(dim == 1){
            namespace poissonProblem = poissonProblem1D;
        }
        else if (dim == 2){
            namespace poissonProblem = poissonProblem2D;
        }
        else if (dim == 3){
            namespace poissonProblem = poissonProblem3D;
        }
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用像后来这样的函数时poissonProblem::eval(),它仍然是使用的函数poissonProblem3D::eval()

您是否有任何想法,或者对其他实施/解决方法的建议?

我不想为每个维度实现代码,因为尽管使用了命名空间,但它几乎是相同的。

谢谢,贾斯特斯

Chr*_*phe 2

您定义的命名空间别名旨在告诉编译器在编译时查找符号时要使用哪个命名空间。

有什么问题 ?

所以当你写的时候

   if(dim == 1) {
        namespace poissonProblem = poissonProblem1D;
    }
Run Code Online (Sandbox Code Playgroud)

您只需为 if-bloc 定义一个命名空间别名即可。一旦你离开街区,它就会被遗忘。

您不应该认为名称空间别名是动态的,可以按照程序的顺序进行更改。

为什么会这样呢?

想象:

namespace poissonProblem1D { 
    class X { 
    public: 
        X(int c) {}   // constructor only with int parameter
        virtual ~X() {} // virtual destructor
    };  // only a constructor with int is allowed
}

namespace poissonProblem2D { 
    class X { 
    public: 
        X() {}   // only constructor without argument
        ~X() {}  //  non virtual destructor
    };  // only a constructor with int is allowed
}
Run Code Online (Sandbox Code Playgroud)

现在假设您可以根据需要在执行流中重新定义命名空间,并且 if 块的执行可以更改命名空间别名。编译器如何编译以下语句:

poissonProblem::X  x(2);  
Run Code Online (Sandbox Code Playgroud)

我们有两种poissonProblem1D::X类型poissonProblem2D::X,但编译器在编译时不知道使用哪一种,哪些是有效或无效参数以及如何生成用于销毁对象 x 的代码。

C++ 具有强大的编译时类型检查,这使得动态命名空间别名成为不可能。

编辑:如何解决?

这取决于上下文。Kerek 已经展示了一种基于模板的方法。

另一种方法是使用条件编译。这对于在编译时配置命名空间非常有用(例如选择使用类的 boost 或 std 版本,例如正则表达式)。

#define dim 2
#if dim==2
        namespace poissonProblem = poissonProblem2D;
#elif dim==1
        namespace poissonProblem = poissonProblem1D;
#elif dim==3
        namespace poissonProblem = poissonProblem3D;
#endif
Run Code Online (Sandbox Code Playgroud)