SFINAE check if expression compiles and return std

2019-03-01 06:34发布

问题:

This question already has an answer here:

  • Is it possible to write a template to check for a function's existence? 25 answers

I want to get std::true_type if the following expression compiles:

template<typename T>
static constexpr std::true_type check(T*) ??????
std::declval<T>().func_name( std::declval<Args>()... ) // method to check for

and std::false_type otherwise which I normally do with

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

I search something like enable_if which returns me a constant type if the expression compiles. Seems so easy but breaks my head :-)

回答1:

I personally use that (which use full signature):

#include <cstdint>

#define DEFINE_HAS_SIGNATURE(traitsName, funcName, signature)               \
    template <typename U, typename... Args>                                 \
    class traitsName                                                        \
    {                                                                       \
    private:                                                                \
        template<typename T, T> struct helper;                              \
        template<typename T>                                                \
        static std::uint8_t check(helper<signature, &funcName>*);           \
        template<typename T> static std::uint16_t check(...);               \
    public:                                                                 \
        static                                                              \
        constexpr bool value = sizeof(check<U>(0)) == sizeof(std::uint8_t); \
    }

So in your case, use something like:

DEFINE_HAS_SIGNATURE(has_func_name, T::func_name, void (T::*)(Args...));

And test it like:

struct C
{
    void func_name(char, int);
};

static_assert(has_func_name<C, char, int>::value, "unexpected non declared void C::func_name(char, int)");
static_assert(!has_func_name<C, int, int>::value, "unexpected declared void C::func_name(int, int)");


标签: c++ c++11 sfinae