To be honest, I dislike virtual dispatching, Interface class. For that reason I want implement own classes without any base abstract class. To be image, I am implementing MyCustomWidget and its some methods have been implemented, others no, because it's not necessary.
// here is my custom widget class, which 'show' method is implemented, but 'close' method is not.
struct MyCustomWidget
{
void show(){ std::cout << "Hey" << std::endl; }
//void close(){ std::cout << "Bye" << std::endl; }
};
// here is your custom widget class, which 'show' is not implemented but 'close' is .
struct YourCustomWidget
{
//void show(){}
void close(){ std::cout << "Bye" << std::endl;}
};
// common widget class, which may stored within any custom widgets.
struct Widget
{
Widget() = default;
template< typename CustomWidget >
void add(CustomWidget cw)
{
auto child = std::make_unique< proxy<CustomWidget> >( std::move( cw ) )
childs.push_back( std::move(child ) );
}
void show()
{
for(auto & e : childs)
e->show();
}
void close()
{
for(auto& e : childs)
e->close();
}
private:
struct proxy_base
{
virtual void show() = 0;
virtual void close() = 0;
virtual ~proxy_base(){}
};
template< typename CustomWidget >
struct proxy : public proxy_base
{
explicit proxy(CustomWidget cw_) : cw( std::move(cw_ ) )
{}
void show() override final
{ // -------------->>>>>> (1)
// call cw.show() if cw has 'show' method, otherwise nothing.
}
void close() override final
{ /// ---------------->>>> (2)
// call cw.close if cw has a 'close' method, otherwise nothing.
}
CustomWidget cw;
};
std::vector< std::unique_ptr< proxy_base > >childs;
};
int main()
{
Widget w;
w.add( MyCustomWidget() );
w.add( YourCustomWidget() );
w.show();
//.... a lot of code
w.close();
}
My Question is simple: how me implement that (1) and (2) virtual methods ?
Edit: I see that question already has been answered. Let me change my question. Q2: (1) and (2) methods are 'final' and in base class they were declared as pure virtual, for this situation compiler can optimize virtual table, and avoid it ? I'm interesting in GCC, CLang and Visual Studio 2013.