說實話,我不喜歡虛擬調度,Interface類。出於這個原因,我想實現自己的類沒有任何基礎的抽象類。爲了形象,我正在實現MyCustomWidget,它的一些方法已經實現,其他方法沒有,因爲它不是必需的。在C++中實現條件虛擬方法11
// 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)虛擬方法?
編輯:我看到那個問題已經被回答。讓我改變我的問題。問題2:(1)和(2)方法是'final'並且在基類中它們被聲明爲純虛擬的,對於這種情況編譯器可以優化虛擬表,並避免它? 我很喜歡GCC,CLang和Visual Studio 2013.
可能重複[是否有可能寫一個C++模板來檢查函數的存在?(http://stackoverflow.com/questions/257288/is-it-possible-to-write -ac-template-to-check-for-a-functions-existence) – KeatsPeeks
我認爲SFINAE成語可以很好地解決您的問題,請參閱我標記爲重複的問題的答案 – KeatsPeeks
ouh,greate !!!謝謝。 – Khurshid