Checking the type of iterator in a container template class

I am writing a container class and want to provide a constructor that takes iterators as a parameter, but only if the corresponding iterated type matches the container type.

So I wrote:

template<typename T>
class Buffer
{
public:
    template <typename InputIter>
    typename std::enable_if<std::is_same<typename std::iterator_traits<InputIter>::value_type, typename T>>::type
    Buffer(InputIter first, InputIter last)
    {
    }
};

But I have compilation errors indicating that the arguments to pattern 1 and 2 are incorrect.

What's wrong?

The code with the compiler is here: https://onlinegdb.com/SyIqN_mBG

+4
source share
2 answers

Almost there. What you need to remember, as you said in the comments, is that constructors do not have return types. The usual SFINAE return type trick will not work for them.

, , SFINAE. , ( ::value), - c'tor:

template<typename T>
class Buffer
{
public:
    template <typename InputIter, 
      typename std::enable_if<std::is_same<typename std::iterator_traits<InputIter>::value_type, T>::value, int>::type = 0>
    Buffer(InputIter first, InputIter last)
    {
    }
};

, , int = 0, , SFINAE! C'tor .

+8

SFINAE 3 :

.

:

template<typename T>
class Buffer
{
public:
    template <typename InputIter,
              typename std::enable_if<
                           std::is_same<typename std::iterator_traits<InputIter>::value_type,
                                        T>::value,
                                      bool>::type = false>
    Buffer(InputIter first, InputIter last)
    {
    }
};
+5

Source: https://habr.com/ru/post/1692538/


All Articles