std::enable_if to conditionally compile a member function

前端 未结 7 2065
执笔经年
执笔经年 2020-11-22 04:57

I am trying to get a simple example to work to understand how to use std::enable_if. After I read this answer, I thought it shouldn\'t be too hard to come up wi

相关标签:
7条回答
  • 2020-11-22 05:51

    The boolean needs to depend on the template parameter being deduced. So an easy way to fix is to use a default boolean parameter:

    template< class T >
    class Y {
    
        public:
            template < bool EnableBool = true, typename = typename std::enable_if<( std::is_same<T, double>::value && EnableBool )>::type >
            T foo() {
                return 10;
            }
    
    };
    

    However, this won't work if you want to overload the member function. Instead, its best to use TICK_MEMBER_REQUIRES from the Tick library:

    template< class T >
    class Y {
    
        public:
            TICK_MEMBER_REQUIRES(std::is_same<T, double>::value)
            T foo() {
                return 10;
            }
    
            TICK_MEMBER_REQUIRES(!std::is_same<T, double>::value)
            T foo() {
                return 10;
            }
    
    };
    

    You can also implement your own member requires macro like this(just in case you don't want to use another library):

    template<long N>
    struct requires_enum
    {
        enum class type
        {
            none,
            all       
        };
    };
    
    
    #define MEMBER_REQUIRES(...) \
    typename requires_enum<__LINE__>::type PrivateRequiresEnum ## __LINE__ = requires_enum<__LINE__>::type::none, \
    class=typename std::enable_if<((PrivateRequiresEnum ## __LINE__ == requires_enum<__LINE__>::type::none) && (__VA_ARGS__))>::type
    
    0 讨论(0)
提交回复
热议问题