在给定重载集和参数列表的情况下,是否可以确定重载决策将选择的候选函数类型?例如,给定:
char* f(int);
int f(char*);
我希望能够写出类似的内容:
overload<f, short>::type x;
声明x
类型的变量char* (*)(int)
。
这可能吗?我的第一直觉是写下这样的东西:
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))
没有。)
答案 0 :(得分:2)
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));
答案 1 :(得分:0)
这是从Convert overloaded function to template functor剥离的。
问题是,你不能将重载函数插入模板,因为它的类型必须是已知的,因此定义一个宏:
#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;