ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 重载成员函数的decltype

2019-10-07 21:07:59  阅读:305  来源: 互联网

标签:c c11 templates variadic-templates template-specialization


参见英文答案 > Disambiguate overloaded member function pointer being passed as template parameter                                    1个
我有这个代码:

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)

以错误告终,这对我来说很清楚.

但是,我如何更加“密切”地指定四种打印方法中的哪一种,我想解析为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(除非你使用的是宏).

标签:c,c11,templates,variadic-templates,template-specialization
来源: https://codeday.me/bug/20191007/1868858.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有