所以我想知道使用私有模板函数是否安全,该函数内部访问传入类型的函数。请记住,我确保自己只能传入这两种类型,并且该函数存在于两者中结构。代码的运行符合我的预期,但我担心它的安全性。有没有更好的方法来达到相同的结果?提前谢谢你:)
类型:
struct Typestruct1
{
int size = 4;
int getSize() {
return size;
}
};
struct Typestruct2
{
int size = 8;
int getSize() {
return size;
}
};
班级:
class MyClass
{
public:
void printSizes() {
std::cout << getSize(t1) << std::endl;
std::cout << getSize(t2) << std::endl;
}
private:
template<typename Type>
int getSize(Type structType) {
return structType.getSize();
}
private:
Typestruct1 t1;
Typestruct2 t2;
};
用途:
MyClass myClass;
myClass.printSizes();
正如我所料,它打印:
4 8
是的,但是您应该创建一个接口,即
Typestruct1
和 Typestruct2
的抽象基类,并带有纯虚函数 virtual int getSize() = 0
,您必须在每个派生类中重写该接口。这样,您就可以保证您打算作为参数传递到模板函数中的每个结构确实具有 int getSize()
函数的实现。就像下面的例子一样:
struct TypestructBase {
virtual int getSize() = 0;
};
struct Typestruct1 : TypestructBase {
int size = 4;
int getSize() override {
return size;
}
};
struct Typestruct2 : TypestructBase {
int size = 8;
int getSize() override {
return size;
}
};
class MyClass {
public:
void printSizes() {
std::cout << getSize(t1) << std::endl;
std::cout << getSize(t2) << std::endl;
}
private:
template<typename Type>
int getSize(Type structType) {
return structType.getSize();
}
Typestruct1 t1;
Typestruct2 t2;
};
int main() {
MyClass myClass;
myClass.printSizes();
return 0;
}