std::is_invocable<...> 检查成员函数

std::is_invocable<...> checking for member function

以下代码正确确定何时可以为给定的 T 调用 Writer( t )

template <typename T>
inline void Process( const T& t )
{
    if constexpr ( std::is_invocable<decltype(Writer), const T&>::value )
    {
        Writer( t );
    }
    else { //... }
}

但我只能让它对 Writer 中定义的 operator() 起作用,例如

class Writer
{
 public:
    operator()( const int& )
    {
        \...
    }
}

我如何获得相同的检查以用于成员函数,即检查该函数是否存在,例如对于 Write(...)

class Writer
{
public:
    inline void Write( const int& t )
    {
    }
};

class Archive
{

public:

    template <typename T>
    inline void Process( const T& t )
    {
        //check if Writer can handle T
        if constexpr ( std::is_invocable_v<decltype( ???&Writer::Write??? ), ???, const T&> )
        {
            TheWriter.Write( t );
            std::cout << "found";
        }
        else
        {    
            std::cout << "not found";
        }
    }

    Writer TheWriter;

};

我在 if constexpr 中尝试的 Writer.WriteWriter::Writedecltype& 的所有可能组合都会导致编译器错误甚至 fatal error C1001.

这是在 Visual Studio 2017 MSVC_1916 上使用 /std:c++17。

您可以像这样检查成员函数:

template <typename T>
inline void Process( const T& t )
{
    if constexpr ( std::is_invocable_v<decltype(&Writer::Write), Writer&, T const &> )    
    {
        Writer{}.Write(t);
    }
    else 
    { 
        //... 
    }
}

这是一个有效的 demo。感谢@aschepler 指出原始片段中的错误。