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 ?
I would like to write a constructor for MyClass that take an argument and
Share
Regrettably, there is no standard way to detect whether a class models
Iterator. The simplest check would be that*itand++itare both syntactically valid; you can do this using standard SFINAE techniques:Considering the
Iteratorrequirements from 24.2.2:2:The problem with trying to use
iterator_traitsis 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_traitson non-iterator types will produce an empty type; you can do a similar trick by checking for the existence ofiterator_categoryon the type:This will however not work for types that do not themselves expose
iterator_categorybut have been adapted by a separateiterator_traitsspecialisation; in that case the simple SFINAE method makes more sense (and you can instantiateiterator_traitswithin the constructor to confirm that the type is iterator-like).