[英]Deducing the selected overloaded function type for given argument types
是否可以確定給定一個重載集和一個參數列表的重載解析將選擇的候選函數的類型? 例如,給定:
char* f(int);
int f(char*);
我希望能夠編寫如下內容:
overload<f, short>::type x;
聲明char* (*)(int)
類型的變量x
。
這可能嗎? 我的本能是寫這樣的東西:
template<typename... Args>
struct overload {
template<typename Ret>
static auto deduce(Ret (*fptr)(Args...)) -> decltype(fptr);
};
...但是這不能處理不完全匹配的內容(即, decltype(overload<int>::deduce(f))
有效,但是decltype(overload<short>::deduce(f))
無效)。
C ++ 14通用lambda來解救:
#define wap_function(f) \
[](auto&&... args){ return f(std::forward<decltype(args)>(args)...); }
請注意,此gem還解決了一流的功能模板的問題:
template<typename Lhs, typename Rhs>
auto add(const Lhs& lhs, const Rhs& rhs)
{
return lhs + rhs;
}
std::accumulate(std::begin(array), std::end(array), 0, wrap_function(add));
這已從“ 將重載函數轉換為模板函子”中刪除。
問題是,您不能將重載函數插入模板,因為必須知道其類型,因此可以定義一個宏:
#define overload_set(f, f_set) \
template <typename ...Args> \
struct f_set { \
typedef decltype(f(std::declval<Args>() ...)) return_type; \
typedef return_type (*) (Args ...) type; \
};
為要使用的每個函數定義結構:
overload_set(f, f_set)
現在可以通過以下方式訪問函數指針類型:
typedef typename f_set<int>::type f_int;
typedef typename f_set<char *>::type f_charptr;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.