Re: Something like a final method
On 21 Mrz., 17:36, Marcel M=FCller <news.5.ma...@spamgourmet.org> wrote:
I would like to avoid these function calls since almost any
method of derived classes do it and the implementation of GetStatus is
really trivial.
Is there any better solution than renaming the method of Interface to
GetStatusByInterface() or something like that?
Looks like the first practical use of [[final]] i noticed. Anyway, why
not do it like this:
// --snip--
class Interface
{public:
Interface(int Status):Status(Status) { }
virtual ~Interface() { }
int GetStatus() { return Status; }
protected:
int Status;
};
class AbstractBase : public Interface
{
AbstractBase():Interface(10){}
};
// --snap--
Another idea could be to abuse overload resolution. But that looks
like an evil way. Though it seems to work
// --snip--
struct not_preferred_t { } not_preferred;
struct preferred_t : not_preferred_t { } preferred;
struct A {
virtual int f(not_preferred_t = not_preferred) = 0;
};
struct B : A {
// don't prefer this one. explicitly give argument not_preferred
// to call it
virtual int f(not_preferred_t) {
return 42;
}
// prefer this one
int f(preferred_t = preferred) {
return 42;
}
};
int main() {
A *a = new B;
cout << a->f(); // slow :(
cout << a->f(preferred); // slow :(
B *b = static_cast<B*>(a);
cout << b->f(not_preferred); // slow :(
cout << b->f(preferred); // fast :)
cout << b->f(); // fast :)
delete b;
}
// --snap--