【问题标题】:C++ template explicit declaration of member function value/ avoiding the problem with macrosC++模板显式声明成员函数值/避免宏问题
【发布时间】:2019-03-19 16:06:59
【问题描述】:

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

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

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

我做了几次尝试,例如:

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 的顺序吗?有解决办法吗?

【问题讨论】:

  • 查找template specialization。它应该告诉你你需要做什么。本质上(如果我没看错的话)您想为特定情况创建特殊版本的模板化代码。

标签: c++ templates c-preprocessor template-specialization


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    相关资源
    最近更新 更多