C 模板明确声明成员函数值/避免了宏的问题

C++ template explicit declaration of member function value/ avoiding the problem with macros

本文关键字:问题 函数 成员 声明      更新时间:2023-10-16

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

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

我对该成员功能有一个特定的请求,generate_mesh:我需要根据 dimspacedim value 明确不同。

我进行了几次尝试,例如:

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

希望预处理器能够进行正确的替代,但结果是未定义的昏暗结果(在两种情况下)。这是因为预处理器替代昏暗的顺序吗?有修复程序吗?

您几乎拥有它。当您专门化模板而不是部分专业化时,您将不包含任何模板参数。这样做会使代码看起来像

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()