[英]Decomposing C++17 function-like object in generic fashion?
在 C++17 假設我有一個類似函數的 object 作為參數傳遞給某個模板:
template<typename F>
void g(F f) {
auto x = f(/*...*/);
}
There are lots of different types F could be, such as a function pointer, a std::function, a lambda expression, and in fact any class type that implements operator()
.
有什么方法可以獲取類似函數的對象的數量及其參數的類型及其返回類型的類型?
我的意思是,最終 F 可能是一個 class ,它使用多個不同的成員函數重載operator()
,每個成員函數都有不同的參數、參數類型和返回類型 - 所以沒有一個完全通用的答案(除非有一些方法可以迭代它重載集,我認為沒有)。
但是對於涉及 f 的 function 調用表達式導致單個重載的典型情況,是否有解決方案?
(如果C++20有什么進展,也值得一提)
C++17 為std::function
添加了推導指南,我們可以使用它來推導非重載類函數對象的 function 簽名:
template <typename R, typename... Args>
constexpr auto do_something_with_the_signature(std::function<R(Args...)>) {
// Assuming that you only care about the return type.
// Otherwise, you may want some kind of wrapper to extract the signature to
// avoid runtime cost
}
...
using some_type_computation =
decltype(do_something_with_the_signature(std::function(f)));
如果您只想要返回類型,您可以使用:
using result_type = typename decltype(std::function(f))::result_type;
如果由於編譯時成本而想完全避免std::function
,則可以為自己的類型實現自己的演繹指南版本(可能與function_traits
類型特征一樣通用)。 在我的回答中可以看到如何自己實施扣除指南的草圖: https://stackoverflow.com/a/66038056/1896169
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.