在stackoverflow上找到了我的许多问题的答案后,我现在遇到了一个我找不到答案的问题,我希望有人愿意帮助我!
我的问题是我想在 C++ 类中对函数进行显式模板化。我的编译器 (g++) 和 C++ 标准 (§14.7.3) 告诉我,这种专业化必须在声明类的命名空间中完成。我知道这意味着我不能将专业化放在班级中,但我不明白这种限制的意义!有谁知道是否有充分的理由不让专业化在课堂上进行?
我知道有解决方法,例如将函数放入结构体中,但我想了解为什么该语言有这种设计。如果有充分的理由不允许在类中使用专门的函数,我想我应该在尝试解决它之前知道它。
提前致谢!
为了使我的问题更精确:这是测试示例中的一些代码,它说明了我想要做的事情:
#include <cstdio>
namespace MalinTester {
template <size_t DIMENSIONALITY>
class SpecializationTest {
public:
SpecializationTest() {
privateVariable = 5;
};
virtual ~SpecializationTest() {};
void execute() {
execute<DIMENSIONALITY>();
};
private:
int privateVariable;
template <size_t currentDim>
static void execute() {
printf("This is the general case. Current dim is %d. The private variable is %d.\n", currentDim, privateVariable);
execute<currentDim-1>();
}
template <>
static void execute<0>() {
printf("This is the base case. Current dim is 0.\n");
}
};
这不可能; g++ 说:
SpecializationTest_fcn.h:27: error: explicit specialization in non-namespace scope ‘class MalinTester::SpecializationTest<DIMENSIONALITY>’
SpecializationTest_fcn.h:28: error: template-id ‘execute<0>’ in declaration of primary template
如果我将函数执行放在类外部的名称空间 MalinTester 中,它将如下所示:
#include <cstdio>
namespace MalinTester {
template <size_t DIMENSIONALITY> class SpecializationTest {};
template <size_t currentDim>
void execute() {
printf("This is the general case. Current dim is %d. The private variable is %d.\n", currentDim, privateVariable);
execute<currentDim-1>();
}
template <>
void execute<0>() {
printf("This is the base case. Current dim is 0.\n");
}
template <size_t DIMENSIONALITY>
class SpecializationTest {
public:
SpecializationTest() {};
virtual ~SpecializationTest() {};
void execute() {
MalinTester::execute<DIMENSIONALITY>();
};
private:
int privateVariable = 5;
};
};
};
我不能在execute 的模板化版本中使用privatevariable,因为它在类中是私有的。我真的want它是私有的,因为我希望尽可能封装我的数据。
当然,我可以将 privateVariable 作为参数发送给函数,但我认为避免这种情况会更漂亮,我真正想知道的是 C++ 标准是否有充分的理由不允许像第一个那样显式专业化上面的代码示例。
@Arne Mertz:这是我尝试过的解决方法,但它也不允许使用 privateVariable。最重要的是,我想知道这样做是否是一个好主意。由于我不允许对成员函数进行专业化,也许我也不应该对封装在类内的结构中的函数进行专业化。
#include <cstdio>
namespace MalinTester {
template <size_t DIMENSIONALITY>
class SpecializationTest {
public:
SpecializationTest() {
privateVariable = 5;
};
virtual ~SpecializationTest() {};
void execute() {
Loop<DIMENSIONALITY, 0>::execute();
};
private:
int privateVariable;
template <size_t currentDim, size_t DUMMY>
struct Loop {
static void execute() {
printf("This is the general case. Current dim is %d.\n", currentDim);
Loop<currentDim-1, 0>::execute();
}
};
template <size_t DUMMY>
struct Loop<0, DUMMY> {
static void execute() {
printf("This is the base case. Current dim is 0.\n");
}
};
};
};