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

前端之家收集整理的这篇文章主要介绍了c – 用于检查是否存在重载成员函数的模板前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果一个类有一个像这样的特殊成员函数(在另一个例子中找到),我尝试专门化一个模板:
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);
};

猜你在找的C&C++相关文章