I would like to write a constructor for MyClass
that take an argument and I want this to compile only if the argument is a pointer
or an iterator
(something having iterator_traits
). How to achieve this ?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Regrettably, there is no standard way to detect whether a class models
Iterator
. The simplest check would be that*it
and++it
are both syntactically valid; you can do this using standard SFINAE techniques:Considering the
Iterator
requirements from 24.2.2:2:The problem with trying to use
iterator_traits
is that it is a template defined for all types, and its instantiation will fail in a non-SFINAE context (recall that SFINAE only applies for direct substitution failure). libstdc++ has a conforming extension whereby instantiatingiterator_traits
on non-iterator types will produce an empty type; you can do a similar trick by checking for the existence ofiterator_category
on the type:This will however not work for types that do not themselves expose
iterator_category
but have been adapted by a separateiterator_traits
specialisation; in that case the simple SFINAE method makes more sense (and you can instantiateiterator_traits
within the constructor to confirm that the type is iterator-like).