mardi 28 novembre 2017

C++ SFINAE and numeric conversions (coercion)

I try to learn SFINAE right now, but it seems I have a problem with coercion, how can I do to make hasRead<Y> and hasRead<Z> fail since the method argument doesn't correspond to an uint_16 ?

I joined my code to see what can be done to make it work like I want !

Thanks in advance :)

#include <cstdint>
#include <iostream>
#include <utility>

template<typename Class>
struct hasRead {
private:
    template<typename T>
    static constexpr auto check(T *) -> typename std::is_same<
        decltype(std::declval<T().read(std::declval<uint16_t>())), uint8_t>::type;


    template<typename>
    static constexpr std::false_type check(...);

    typedef decltype(check<Class>(0)) type;

public:
    static constexpr bool value = type::value;
};

struct X {
    uint8_t read(uint16_t x) { return 3; }
};

struct Y {
    uint8_t read(uint8_t x) { return 3; }
};

struct Z {
    uint8_t read(int64_t x) { return 3; }
};

static_assert(hasRead<X>, "");
static_assert(hasRead<Y>, "");
static_assert(hasRead<Z>, "");

Aucun commentaire:

Enregistrer un commentaire