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

Kla*_*aus 5 c++ templates metaprogramming

如果一个类有一个像这样的特殊成员函数(在另一个例子中找到),我尝试专门化一个模板:

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 };
};
Run Code Online (Sandbox Code Playgroud)

这很有效,直到AnyFunc重载:

class B : public vector<int>
{
public:
    void AnyFunc() const;
    void AnyFunc();
};
Run Code Online (Sandbox Code Playgroud)

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

Pio*_*ycz 1

找到了有效的版本:

    template <typename C> static one test( decltype(((C*)0)->AnyFunc())* ) ;
Run Code Online (Sandbox Code Playgroud)

如果要验证对象是否具有 const 函数,请使用以下命令:

    template <typename C> static one test( decltype(((const C*)0)->AnyFunc())* ) ;
Run Code Online (Sandbox Code Playgroud)

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

class B : public std::vector<int>
{
public:
    //void AnyFunc() const;
    //void AnyFunc();
    int AnyFunc(int);
};
Run Code Online (Sandbox Code Playgroud)