C 模板明确声明成员函数值/避免了宏的问题
C++ template explicit declaration of member function value/ avoiding the problem with macros
我认为这会更容易;我有这样的类:
template <int dim, int spacedim>
class FE_problem
{
//...
void generate_mesh();
}
我对该成员功能有一个特定的请求,generate_mesh
:我需要根据 dim
和 spacedim
的 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()
相关文章:
- Visual Studio中的函数声明和函数定义问题
- C++quit()函数中可能存在作用域问题
- 类似于strcat()的函数出现问题
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 类C++中的函数问题(LNK2019和LNK1120错误)
- c++binary_search函数排序数组(流行名称搜索)出现问题
- 关于简单C++函数(is_palindrome)的逻辑的问题
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- constexpr构造函数需要常量成员函数时出现问题
- 添加存储在向量中的大整数的函数出现问题
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 关于 c++ 函数中指针赋值的简单问题
- 如何在标头中声明(或定义)函数的问题
- 有关 c++ 构造函数的问题
- 模板类转换问题 - 无法推断调用的函数
- 从 C++ 中的函数返回数组地址问题
- 关于复制构造函数的一个棘手问题
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题