我有一個將被用作不同的論點職能一些自定義類型:遞歸調用重載C++函數
struct A {};
struct B {};
struct C {};
struct D {};
struct E {};
也有一些函數返回仿函數包裝:
template <typename H>
auto foo (H h,
enable_if_t<is_same<typename result_of<H(A)>::type, bool>::value>* = 0)
{
return [h] (B x) { return h (A {}); };
}
這把H(A)仿函數轉換成G(B)仿函數,它將輸入參數B-> A(在這裏爲簡單起見不實現)並且用A來調用H。
我有類似的con vertors C-> B,D-> C,E-> d:
template <typename H>
auto foo (H h,
enable_if_t<is_same<typename result_of<H(B)>::type, bool>::value>* = 0)
{
return [h] (C x) { return h (B {}); };
}
template <typename H>
auto foo (H h,
enable_if_t<is_same<typename result_of<H(C)>::type, bool>::value>* = 0)
{
return [h] (D x) { return h (C {}); };
}
template <typename H>
auto foo (H h,
enable_if_t<is_same<typename result_of<H(D)>::type, bool>::value>* = 0)
{
return [h] (E x) { return h (D {}); };
}
現在我可以調用foo 4次,將得到獲取型 「E」 的說法函子,最後調用與內部處理程序參數「A」:
auto inner_handler = [] (A) -> bool { return false; };
auto f = foo (foo (foo (foo (inner_handler))));
f (E {});
我想是實現call_until功能稱之爲「foo」的重載遞歸直到產生仿函數參數類型成爲T.
假設轉換器的從A路徑到E永遠存在,並且恰好是一個。換句話說,我想表達
auto f = call_until<E> (inner_handler);
工作完全一樣
auto f = foo (foo (foo (foo (inner_handler))));
我是從像開始:
template <typename Stop, typename Handler, typename Result>
struct call_until_helper
{
Handler handler_;
call_until_helper (Handler h) : handler (h) {}
};
template <typename Stop, typename Handler>
call_until_helper<Stop, Handler,
typename boost::function_traits<Handler>::result_type>
call_until (Handler handler)
{
return call_until_helper<Stop, Handler,
typename boost::function_traits<Handler>::result_type> (handler);
}
但我得到的編譯錯誤還挺停留在這點。我需要一些想法來實現這一點。
嘗試使用' - >'表示「從左手邊接受參數,並返回右邊」,因爲這更傳統的功能符號相匹配。所以有一個超載'foo:''H:A-> bool'' - >''G:B-> bool'。爲了讓你的代碼更清潔,你可以用'result_of_t'替換'result_of'嗎?如果您的編譯器沒有它,請使用result_of_t = typename std :: result_of :: type;'編寫一個模板。噪音較小。 –
Yakk
2015-02-06 20:07:41