Home > Mobile >  Detect if C class has a template method
Detect if C class has a template method

Time:11-27

I know how to detect presence of a variable or a regular method in a C class. But how to do it, when the method is a template? Consider the code:

struct SomeClass
{
    template<typename Sender, typename T>
    auto& send(T& object) const
    {
        Sender::send(object);
        return object;
    };
};

How to write something like is_sendable so that is_sendable<SomeClass>::value (or any other syntax) returns true because SomeClass has method send like above ?

CodePudding user response:

Ok, I acutally managed to solve it, if anyone is interested:

I needed to create a dummy class

class DummySender
{
    public:
        template<typename T>
        static void send(const T&)
        {}
};

And then I can check for the presence of the send method, by defining type traits:

template<typename T, typename = void>
struct IsSendable: std::false_type
{};

template<typename T>
struct IsSendable<T, decltype(std::declval<T>().send<DummySender>(std::cout), void())> : std::true_type
{};

To finally have IsSendable<SomeClass>::value.

  • Related