Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I static_assert the type that an iterator dereferences to?

Tags:

c++

template <typename InputIterator>
MyFun(const InputIterator begin, const InputIterator end)
{
    // I want to static_assert that decltype(*begin) == SomeType
}

How can I do this? I'm thinking static_assert(std::is_same<*InputIterator,SomeType>) but that of course does not work...

like image 543
quant Avatar asked Sep 16 '25 22:09

quant


2 Answers

std::iterator_traits:

static_assert(is_same<typename std::iterator_traits<InputIterator>::value_type, 
               SomeType>::value, "");
like image 72
Jesse Good Avatar answered Sep 19 '25 13:09

Jesse Good


An alternative using decltype, with a note in passing that it often produces a reference (but may not!).

// If you want to assert that the dereferenced item is indeed a reference
static_assert(std::is_same<decltype(*begin), SomeType&>::value, "");

// If you are only interested in the "bare" type
// (equivalent to Jesse's providing iterator_traits was properly specialized)
static_assert(std::is_same<
    typename std::remove_reference<decltype(*begin)>::type,
    SomeType
>::value, "");
like image 36
Matthieu M. Avatar answered Sep 19 '25 13:09

Matthieu M.