我如何static_assert迭代器取消引用的类型?

时间:2013-10-15 04:49:04

标签: c++

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

我该怎么做?我在想static_assert(std::is_same<*InputIterator,SomeType>),但那当然不起作用......

2 个答案:

答案 0 :(得分:7)

std::iterator_traits

static_assert(is_same<typename std::iterator_traits<InputIterator>::value_type, 
               SomeType>::value, "");

答案 1 :(得分:2)

另一种使用decltype的替代方法,传递一个注释,它经常产生一个引用(但可能不会!)。

// 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, "");