non-user38741
non-user38741

Reputation: 871

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

The following code correctly determines when Writer( t ) can be called for a given T.

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

But I can only get this to work for operator() defined in Writer as e.g.

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

How do I get the same check to work for a member function, i.e check if that function exists, e.g. for Write(...) in

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;

};

Every conceivable combination of Writer.Write, Writer::Write, decltype and & that I tried in the if constexpr results in a compiler error or even fatal error C1001.

This is on Visual Studio 2017 MSVC_1916 with /std:c++17.

Upvotes: 3

Views: 5161

Answers (1)

cigien
cigien

Reputation: 60238

You can check for a member function like this:

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 
    { 
        //... 
    }
}

Here's a working demo. Thanks @aschepler for pointing out the mistake in the original snippet.

Upvotes: 8

Related Questions