Substitution failure is not an error (SFINAE) for enum

前端 未结 1 1878
不思量自难忘°
不思量自难忘° 2021-01-21 02:39

Is there a way to use Substitution failure is not an error (SFINAE) for enum?

template 
struct Traits
{
}
template <>
struct Traits

        
相关标签:
1条回答
  • 2021-01-21 03:33

    If you can use C++11, this is completely trivial:

    template<class T>
    struct has_nested_option{
      typedef char yes;
      typedef yes (&no)[2];
    
      template<class U>
      static yes test(decltype(U::option)*);
      template<class U>
      static no  test(...);
    
      static bool const value = sizeof(test<T>(0)) == sizeof(yes);
    };
    

    The C++03 version is (surprisingly) similar:

    template<class T>
    struct has_nested_option{
      typedef char yes;
      typedef yes (&no)[2];
    
      template<int>
      struct test2;
    
      template<class U>
      static yes test(test2<U::option>*);
      template<class U>
      static no  test(...);
    
      static bool const value = sizeof(test<T>(0)) == sizeof(yes);
    };
    

    Usage:

    struct foo{
      enum { option = 1 };
    };
    
    struct bar{};
    
    #include <type_traits>
    
    template<class T>
    typename std::enable_if<
      has_nested_option<T>::value
    >::type Do(){
    }
    
    int main(){
      Do<foo>();
      Do<bar>(); // error here, since you provided no other viable overload
    }
    
    0 讨论(0)
提交回复
热议问题