Check the existence of a template function

Viewed 217

How can I check the existence of a template function like this: Checking if reader struct has read arithmetic value

struct reader {
    template<typename T>
    std::enable_if_t<std::is_arithmetic<T>::value, T> read() {
        return {};
    }
};

I use a checker like this:

template <typename T>
struct test_read {
    static constexpr auto value = std::is_convertible<decltype(std::declval<T>().read<int>()),int>::value;      
};

But the compiler complains:

error: wrong number of template arguments (1, should be 2)
 static constexpr auto value = std::is_convertible<decltype(std::declval<T>().read<int>()),int>::value;

Please give me your advice on that.

Thank you.


Update: Here is the final version I got after discussion, I hope everyone will find it helpful for your code

struct not_reader {

};


struct reader {
    template<typename T>
    std::enable_if_t<std::is_arithmetic<T>::value, T> read() {
        return {};
    }
};


template<class T, class Elem>
struct has_read {
private:
    template<class C, typename=void>
    struct test_read : std::false_type {
    };
    template<class C>
    struct test_read<C, typename std::enable_if<std::is_convertible<decltype(std::declval<C>().template read<Elem>()), Elem>::value>::type>
            : std::true_type {
    };
public:
    using type = typename test_read<T>::type;
    static constexpr bool value = test_read<T>::value;
};


static_assert(has_read<reader, int>::value, "reader should have int read()");
static_assert(!has_read<not_reader, int>::value, "not_reader should not have int read()");
2 Answers
Related