SFINAE check if expression compiles and return std::true_type [duplicate]

久未见 提交于 2019-12-02 06:35:58

问题


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)");


来源:https://stackoverflow.com/questions/23547654/sfinae-check-if-expression-compiles-and-return-stdtrue-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!