c++ - C++模板显式声明成员函数值/避免宏问题
问题描述
我认为这会更容易;我有这样的一类:
template <int dim, int spacedim>
class FE_problem
{
//...
void generate_mesh();
}
我对那个成员函数有一个特殊的要求generate_mesh
:我需要它根据and的值显式不同。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 <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()
推荐阅读
- javascript - Moment.js 更改午夜时间重置
- python - 在具有不同移位长度的多列上使用 pandas .shift
- javascript - Sedo api 响应错误——SOAP Javascript 客户端
- asp.net - 如何向 NEST 添加多个字段?
- javascript - Vue 3 composition api typescript 从路由查询中填充对象属性
- vba - 对于移动文件夹的每个循环遍历文件夹正在跳过一些文件夹
- java - TelephonyManager 为所有参数抛出错误。用户 10449 不满足访问设备标识符的要求
- java - 从空 sharedpreference 中检索 json 数组时,java.lang.String 无法转换为 JSONObject 异常出现
- javascript - Javascript _ 点符号和括号符号
- android - 颤动路径错误 PATH="$PATH":"$HOME/.pub-cache/bin"