0x5*_*9df 8 c++ templates overload-resolution template-meta-programming c++11
在给定重载集和参数列表的情况下,是否可以确定重载决策将选择的候选函数类型?例如,给定:
char* f(int);
int f(char*);
Run Code Online (Sandbox Code Playgroud)
我希望能够写出如下内容:
overload<f, short>::type x;
Run Code Online (Sandbox Code Playgroud)
声明一个x
类型的变量char* (*)(int)
.
这可能吗?我的第一直觉是写下这样的东西:
template<typename... Args>
struct overload {
template<typename Ret>
static auto deduce(Ret (*fptr)(Args...)) -> decltype(fptr);
};
Run Code Online (Sandbox Code Playgroud)
...但是这不能处理非完全匹配(即decltype(overload<int>::deduce(f))
工作,但decltype(overload<short>::deduce(f))
不能).
这是从Convert 重载函数到模板函子中剥离的。
问题是,您不能将重载函数插入到模板中,因为它的类型必须已知,因此定义一个宏:
#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; \
};
Run Code Online (Sandbox Code Playgroud)
为您要使用的每个函数定义结构:
overload_set(f, f_set)
Run Code Online (Sandbox Code Playgroud)
现在可以通过以下方式访问函数指针类型:
typedef typename f_set<int>::type f_int;
typedef typename f_set<char *>::type f_charptr;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
451 次 |
最近记录: |