ICode9

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

c – 检查是否存在(重载)成员函数

2019-10-06 08:16:38  阅读:259  来源: 互联网

标签:c c11 templates sfinae


关于检查成员函数是否存在,有许多已回答的问题:例如,
Is it possible to write a template to check for a function’s existence?

但是,如果函数重载,此方法将失败.这是一个稍微修改过的代码,来自该问题的最高评价答案.

#include <iostream>
#include <vector>

struct Hello
{
    int helloworld(int x)  { return 0; }
    int helloworld(std::vector<int> x) { return 0; }
};

struct Generic {};


// SFINAE test
template <typename T>
class has_helloworld
{
    typedef char one;
    typedef long two;

    template <typename C> static one test( decltype(&C::helloworld) ) ;
    template <typename C> static two test(...);


public:
    enum { value = sizeof(test<T>(0)) == sizeof(char) };
};


int
main(int argc, char *argv[])
{
    std::cout << has_helloworld<Hello>::value << std::endl;
    std::cout << has_helloworld<Generic>::value << std::endl;
    return 0;
}

这段代码打印出来:

0
0

但:

1
0

如果第二个helloworld()被注释掉了.

所以我的问题是是否可以检查成员函数是否存在,无论它是否过载.

解决方法:

在C中,不可能[到目前为止]取一个重载集的地址:当你获取一个函数或一个成员函数的地址时,该函数要么是唯一的,要么必须选择适当的指针,例如,通过指针直接指向合适的函数或通过强制转换它.换句话说,如果helloworld不是唯一的,那么表达式& C :: helloworld就会失败.据我所知,结果是无法确定可能重载的名称是作为类成员还是作为普通函数出现.

通常,您需要对名称执行某些操作.也就是说,如果知道某个函数是否存在并且可以使用指定类型的一组参数调用就足够了,那么问题会变得很不一样:可以通过尝试相应的调用并在其中确定其类型来回答这个问题.具有SFINAE能力的背景,例如:

template <typename T, typename... Args>
class has_helloworld
{
    template <typename C,
              typename = decltype( std::declval<C>().helloworld(std::declval<Args>()...) )>
    static std::true_type test(int);
    template <typename C>
    static std::false_type test(...);

public:
    static constexpr bool value = decltype(test<T>(0))::value;
};

然后,您可以使用此类型来确定是否存在可以适当调用的成员,例如:

std::cout << std::boolalpha
          << has_helloworld<Hello>::value << '\n'       // false
          << has_helloworld<Hello, int>::value << '\n'  // true
          << has_helloworld<Generic>::value << '\n';    // false

标签:c,c11,templates,sfinae
来源: https://codeday.me/bug/20191006/1859515.html

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

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

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

ICode9版权所有