【发布时间】:2014-02-18 17:58:00
【问题描述】:
说实话,我不喜欢虚拟调度,接口类。出于这个原因,我想实现自己的类,而不需要任何基础抽象类。为了形象,我正在实现 MyCustomWidget 并且它的一些方法已经实现,其他没有,因为它不是必需的。
// 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();
}
我的问题很简单:我如何实现 (1) 和 (2) 虚拟方法?
编辑:我看到这个问题已经得到回答。让我换个问题。 Q2:(1)和(2)方法是'final'并且在基类中它们被声明为纯虚拟,对于这种情况编译器可以优化虚拟表,并避免它? 我对 GCC、CLang 和 Visual Studio 2013 很感兴趣。
【问题讨论】:
-
我认为 SFINAE 成语完美地解决了您的问题,请参阅我标记为重复的问题的答案
-
哦,太好了!!!谢谢。
-
我真的不明白跳过所有这些圈以摆脱几个虚函数指针的意义。与 GUI 函数的典型代码量相比,引用它们所需的时间完全可以忽略不计,因此性能几乎不是问题。您可以轻松地在继承链的顶部生成默认虚拟方法并摆脱问题。相比之下,模板 goo 使代码变得臃肿、不可读且编译缓慢(并且会喷出令人眼花缭乱的错误消息来惩罚你最轻微的拼写错误)。恕我直言,这几乎不是一个好的交换。
-
这只是一个例子,我不是GUI程序员。但我同意你的看法。
标签: c++ c++11 dispatch virtual-functions