SFINAE compiler troubles

前端 未结 5 1014
一向
一向 2021-02-06 08:54

The following code of mine should detect whether T has begin and end methods:

template 
struct is_contai         


        
5条回答
  •  别那么骄傲
    2021-02-06 09:27

    With C++11, there are now better ways to detect this. Instead of relying on the signature of functions, we simply call them in an expression SFINAE context:

    #include  // declval
    
    template
    class is_container{
      typedef char (&two)[2];
    
      template // non-const
      static auto test(typename U::iterator*, int)
          -> decltype(std::declval().begin(), char());
    
      template // const
      static auto test(typename U::const_iterator*, long)
          -> decltype(std::declval().begin(), char());
    
      template
      static two  test(...);
    
    public:
      static bool const value = sizeof(test(0, 0)) == 1;
    };
    

    Live example on Ideone. The int and long parameters are only to disambiguate overload resolution when the container offers both (or if iterator is typedef const_iterator iterator, like std::set is allowed to) - literal 0 is of type int and forces the first overload to be chosen.

提交回复
热议问题