假設以下兩個功能可能會或可能不會被用戶提供:選擇功能通過元編程
void foo(int) { std::cout << "foo int" << std::endl; }
void foo() { std::cout << "foo void" << std::endl; }
在我的實現,我想打電話給foo(int)
如果用戶定義它,否則foo()
。這可以如下進行:
template<class Int> auto call_foo(Int i) -> decltype(foo(i)) { return foo(i); }
template<class... Int> void call_foo(Int... i) { return foo(); }
但是,如果我們想反其道而行之,即寧願foo()
超過foo(int)
,下面的天真嘗試不起作用。
template<class Int> auto call_foo(Int i) -> decltype(foo()) { return foo(); }
template<class... Int> void call_foo(Int... i) { return foo(i...); }
的問題是,decltype(foo())
不依賴於Int
,所以foo()
可能不存在不SFINAE結果。
一種可能的解決辦法是要求用戶定義的
void foo(int, void*) { std::cout << "foo int" << std::endl; }
void foo(void*) { std::cout << "foo void" << std::endl; }
像這樣無論是,我們總是有foo
參數上,我們可以做的「模板與參數包」的把戲。雖然這在技術上解決了這個問題,但它很難看,因爲它要求用戶採取一個額外的參數,這個參數對他/她來說可能並不明顯。那麼有沒有辦法達到同樣的效果沒有的附加參數?
它似乎沒有與叮噹 – 2014-10-03 09:00:40
非常有用的技巧,這個標籤繼承。我在這裏清理你的代碼:http://stackoverflow.com/questions/26176516/choose-best-available-function-through-tag-inheritance – gTcV 2014-10-03 09:31:16
@MarcoA .:刪除'= delete'似乎解決了錯誤與叮噹聲。 – Jarod42 2014-10-03 09:44:18