templates - C++ same name for non-virtual function in derived class conflicts with `final` specifier -


this has feeling of complete newbie question, why following code not compile when final specifier used b::operator()?

struct {     virtual void operator()() const = 0; };  // crtp-component not necessary here // possibly makes more sense in applied in reality // template<typename derived> struct b : {     virtual void operator()() const override final     {         static_cast<derived const&>(*this).operator()();     } };  struct c : b<c> {     void operator()() const     {         //do     } };  int main() {     c()(); } 

g++ prints following error message:

main.cpp:17:14: error: virtual function 'virtual void c::operator()() const'          void operator()() const               ^ main.cpp:9:22: error: overriding final function 'void b<derived>::operator()() const [with derived = c]'          virtual void operator()() const override final                       ^ 

i have thought works non-virtual c::operator() not override virtual functions in base classes? how can bring work (--without changing name of c::operator())?


edit: pointed out several users, answer virtual-keyword in derived class redundant (whereas thought leaving out prevent inheriting). however, goal had in asking -- namely a consistent interface throughout dynamic , static inheritance hierarchy -- can solved using non-virtual operator[] throughout , couple classes a , b virtual function apply:

struct {     void operator()() const     {         this->apply();     }  protected:     virtual void apply() const = 0; };  template<typename derived> struct b : {     void operator()() const     {         static_cast<derived const&>(*this).operator()();     }  protected:     virtual void apply() const override final     {         this->operator()();     } };  struct c : b<c> {     void operator()() const     {         //do     } };  int main() {     c()(); } 

a function in derived class same signature virtual function in base class overrides virtual function base class. makes virtual function, if/though declaration in derived class doesn't use virtual key word.

that can't changed, if really need have function same name in derived class doesn't override virtual function base class (and in process, become virtual , in case, violate final in b) you'll need change signature of function in derived class. can mean different name, different parameter list, or different qualifiers. i'd treat latter 2 extreme caution though--the compiler able sort out mess you've made, many human readers may (very easily) surprised.

if reviewing such code, i'd cite problem, , author need provide solid reasoning why necessary approved.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -