重载成员函数的解除类型
decltype for overloaded member function
我有这样的代码:
struct Foo
{
int print(int a, double b);
int print(int a);
void print();
void print(int a, int b, int c);
void other();
};
我可以调用
decltype(&Foo::other)
但调用
decltype(&Foo::print)
以error结束,这对我来说很清楚。
但是,我如何更"紧密地"指定四个print
方法中的哪一个,我想解析为decltype
?
template <class MT>
struct method_info;
template <class T, class Res, class... Args>
struct method_info<Res(T::*)(Args...)>
{
typedef std::tuple<Args&&...> args_tuple;
typedef T ClassType;
typedef Res RetVal;
};
template <class MethodType>
void func() {
typedef method_info<MethodType> MethodInfo;
.....
}
func<decltype(&Foo::other)>();
....
更"紧密",据我所知,意味着你想指定print
的函数参数。也就是说,例如,选择int, int
,然后返回Foo{}.print(int{},int{})
的结果类型,然后从所有可用的信息构造一个函数指针。
这是一个别名模板,它以一种通用的方式为你做:
template<typename ... Args>
using ptr_to_print_type = decltype(std::declval<Foo>().print(std::declval<Args>() ...)) (Foo::*)(Args ...);
你也可以用std::result_of
代替std::declval
的东西,但我更喜欢后者。
你可以使用上面的
func<ptr_to_print_type<int,int> >();
编辑:根据@JavaLover的要求,顺便说一句,对于这种可怕的c++狗屎来说,这似乎是一个不合适的名字:-),这里与上面使用std::result_of
相同(未测试现在测试和错误):
//------ does not compile for overloaded functions --------
template<typename ... Args>
using ptr_to_print_type = std::result_of_t<decltype(&Foo::print)(Foo, Args ...)> (Foo::*)(Args ...)
//------ does not compile for overloaded functions --------
您可以进一步抽象Foo
,但不能抽象print
(除非使用宏)。
不确定确切的语法,但是,在方法名称重载的情况下,您应该强制转换指针;就像
static_cast<void(Foo::*)(int, int, int)>(&Foo::print);
如果您只对类型感兴趣,则应该是强制转换的模板值
void(Foo::*)(int, int, int)
相关文章:
- 访问C++中的类型成员
- 具有 STL 向量类型成员的类的复制内存
- 重载具有 2 个相同数据类型成员的构造函数
- std::void_t 和嵌套的非类型成员
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 使用各种数据类型成员创建对象的简便方法
- 将类类型成员定义为公共和私有之间有什么区别?
- 结构类型成员的默认构造函数中的默认参数
- 如何传递模板模板非类型成员函数指针
- 文本类类型成员函数约束
- 给定仅包含布尔类型成员的结构的两个对象 s1 和 s2,只要 s1 的成员为 true,请检查 s2 的每个成员是否为真
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- C++:将模板参数的模板类型成员加为好友的语法正确吗
- C++静态结构类型成员初始化
- C++:作为引用或指针的基类型成员变量
- 左值引用类型成员的用户定义移动构造函数
- 具有指针类型成员的类在 MSVS2012@debug 下销毁时失败.程序错误或错误源
- CRTP -- 访问不完整的类型成员
- 为什么C++默认初始化不对非类类型成员进行零初始化
- 请求非类类型成员