[英]Preventing a static method in base class from being called through derived class?
I have a Base class, and a Derived template that inherits from it.我有一个 Base class,以及一个从它继承的 Derived 模板。 Both of these define a static method
calculateSize()
but with different method signatures.这两个都定义了一个 static 方法
calculateSize()
但具有不同的方法签名。 (Both are also instanced as objects; Base isn't just an interface.) (两者都被实例化为对象;Base 不仅仅是一个接口。)
class Base{
public:
static size_t calculateSize(size_t payload);
};
template<typename T>
class Derived : public Base{
public:
// sloppy fixo to prevent Base::calc() from being called
static size_t calculateSize(size_t){ assert(0); return calculateSize(); }
// correct method to call
static size_t calculateSize();
};
The Base class's version of this method would give a wrong answer if called for a Derived type, so I want to prevent it from accidentally being called through Derived::calculateSize(sz)
.如果调用 Derived 类型,则此方法的 Base 类版本会给出错误答案,因此我想防止通过
Derived::calculateSize(sz)
意外调用它。 How would this typically be accomplished?这通常是如何实现的? (I currently have a method with the same signature in
Derived
that asserts if called, this feels kinda hacky though...) (我目前在
Derived
中有一个具有相同签名的方法,如果被调用则断言,虽然这感觉有点老套......)
If you have a calculateSize
in the derived class, it will hide calculateSize
in the base class, so you can simply just not have anything:如果您在派生的 class 中有一个
calculateSize
,它将在基数 class 中隐藏calculateSize
,因此您可以简单地没有任何东西:
template<typename T>
class Derived : public Base {
public:
static size_t calculateSize();
};
// Error: no function that takes an argument
size_t result = Derived<int>::calculateSize(1);
If you don't have something to hide it or you want it to be more clear that you shouldn't call it with the base classes signature, you can = delete
it:如果你没有什么东西可以隐藏它或者你想让它更清楚你不应该用基类签名调用它,你可以
= delete
它:
template<typename T>
class Derived : public Base {
public:
// Explanatory comment here
static size_t calculateSize(size_t) = delete;
static size_t calculateSize();
};
// Error: trying to use deleted function
size_t result = Derived<int>::calculateSize(1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.