问题
template<typename Iterator>
void put_value(Iterator pos, int n)
{
static_assert(IsOutputIterator<Iterator>);
//
// How to implement IsOutputIterator?
//
*pos = n;
}
std::iterator_traits<Iterator>::iterator_category
doesn't help. For example: vector<int>::iterator
is obvious an output_iterator
, but std::iterator_traits<vector<int>::iterator>::iterator_category
will returns random_access_iterator
, which might not be an output_iterator
, say a const_iterator
.
Is there any viable way to check if an iterator is an output_iterator in c++?
回答1:
My first response is to ask "Output iterator for what?" C++ output iterators don't specify a value type, because the same iterator may be able to output multiple value types. The only way to determine if you can write a given expression E
through a given iterator o
is to see if *o = std::declval<decltype((E))>()
is a valid expression.
In C++14, I'd define a trait to do so:
template <class...> using void_t = void;
template <class, class, class = void>
constexpr bool is_output_iterator = false;
template <class I, class E>
constexpr bool is_output_iterator<I, E, void_t<
typename std::iterator_traits<I>::iterator_category,
decltype(*std::declval<I>() = std::declval<E>())>> = true;
In C++ with concepts - which I assume you are interested in since you tagged this question with c++-concepts - I would grab the sample Ranges TS implementation from github and use its OutputIterator<I, E>()
concept instead.
来源:https://stackoverflow.com/questions/40901170/how-to-check-if-an-iterator-is-an-output-iterator-in-c