SFINAE检查表达式是否编译并返回std :: true_type [英] SFINAE check if expression compiles and return std::true_type

查看:73
本文介绍了SFINAE检查表达式是否编译并返回std :: true_type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要编译以下表达式,我想获取std :: true_type:

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

和std :: false_type,否则我通常会这样做

and std::false_type otherwise which I normally do with

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

我搜索诸如enable_if之类的东西,如果表达式编译,它将返回一个常量类型.似乎很容易,但伤了我的头:-)

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

推荐答案

我个人使用它(使用完整签名):

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

并像这样测试它:

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

这篇关于SFINAE检查表达式是否编译并返回std :: true_type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆