加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 用于检查是否存在重载成员函数的模板

发布时间:2020-12-16 05:02:12 所属栏目:百科 来源:网络整理
导读:如果一个类有一个像这样的特殊成员函数(在另一个例子中找到),我尝试专门化一个模板: template typename Tclass has_begin{ typedef char one; typedef long two; template typename C static one test( decltype( C::AnyFunc) ) ; template typename C stat
如果一个类有一个像这样的特殊成员函数(在另一个例子中找到),我尝试专门化一个模板:
template <typename T>
class has_begin
{
    typedef char one;
    typedef long two;

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

public:
    enum { value = sizeof(test<T>(0)) == sizeof(char) };
    enum { Yes = sizeof(has_begin<T>::test<T>(0)) == 1 };
    enum { No = !Yes };
};

这很有效,直到AnyFunc重载:

class B : public vector<int>
{
public:
    void AnyFunc() const;
    void AnyFunc();
};

如何从我的模板中重写我的测试代码以获得“是”?

解决方法

找到有效的版本:
template <typename C> static one test( decltype(((C*)0)->AnyFunc())* ) ;

如果要验证该对象是否具有const函数,请使用:

template <typename C> static one test( decltype(((const C*)0)->AnyFunc())* ) ;

此版本不会检测带参数的函数:

class B : public std::vector<int>
{
public:
    //void AnyFunc() const;
    //void AnyFunc();
    int AnyFunc(int);
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读