首页 > 解决方案 > C++模板显式声明成员函数值/避免宏问题

问题描述

我认为这会更容易;我有这样的一类:

template <int dim, int spacedim>
class FE_problem
{
    //...
   void generate_mesh();
}

我对那个成员函数有一个特殊的要求generate_mesh:我需要它根据and的显式不同。dimspacedim

我做了几次尝试,例如:

template <int dim, int spacedim>
void FE_problem<1, 3>::generate_mesh()
{
...do a kind of mesh initialization ...
}

template <int dim, int spacedim>
void FE_problem<3, 3>::generate_mesh()
{
...do another kind of mesh initialization ...
}

但无法编译。

我尝试使用std::enable_if,但我仍然不太了解它是如何工作的,我不知道它是否是正确的方法。

为了避免(现在)我尝试使用宏的问题,在定义方法时使用以下代码:

#if DIM 1
template <int dim, int spacedim>
void FE_problem<dim,spacedim>::generate_mesh()
{
...do a kind of mesh initialization ...
}
#elif DIM 3
template <int dim, int spacedim>
void FE_problem<dim,spacedim>::generate_mesh()
{
...do another kind of mesh initialization ...
}
#endif

然后,在函数中初始化类时main,我尝试了类似的方法:

#define DIM 1
auto FE1 = FE_problem<1, 3>();
#undef DIM

#define DIM 3
auto FE2 = FE_problem<1, 3>();
#undef DIM

希望预处理器能做正确的替换,但结果是 DIM 结果未定义(在这两种情况下)。这是因为预处理器替换 DIM 的顺序吗?有解决办法吗?

标签: c++templatesc-preprocessortemplate-specialization

解决方案


你几乎拥有它。当您特化模板并且它不是部分特化时,您不包含任何模板参数。这样做会使代码看起来像

template <int dim, int spacedim>
class FE_problem
{
public:
   void generate_mesh();
};

template <> // full specialization, leave template parameter blank as they are provided below
void FE_problem<1, 3>::generate_mesh()
//              ^^^^ specify the specialized types/values here  
{
    std::cout << "void FE_problem<1, 3>::generate_mesh()\n";
}

template <> // full specialization, leave template parameter blank as they are provided below
void FE_problem<3, 3>::generate_mesh()
//              ^^^^ specify the specialized types/values here  
{
    std::cout << "void FE_problem<3, 3>::generate_mesh()\n";
}

int main()
{
    FE_problem<1, 3>{}.generate_mesh();
    FE_problem<3, 3>{}.generate_mesh();
}

哪个输出

void FE_problem<1, 3>::generate_mesh()
void FE_problem<3, 3>::generate_mesh()

推荐阅读