nib*_*shi 14 c++ templates iterator template-specialization
可以通过它来专门化Iterator模板参数value_type吗?
我有一个功能与以下原型.
template<typename InputIterator>
void f(InputIterator first, InputIterator last);
Run Code Online (Sandbox Code Playgroud)
如果InputIterator::value_type是,我想特别处理SomeSpecificType.
您可以使用一些中间结构来获得所需的部分模板特化.这样的事情应该可以解决问题
template<typename T, typename V>
struct f_impl
{
static void f( T first, T last ) {...}; //Default version
};
template<typename T>
struct f_impl<T, SomeSpecificType>
{
static void f(T first,T last) {...}; //Specialisation
};
template<typename InputIterator> void f(InputIterator first, InputIterator last)
{
f_impl<
InputIterator,
typename std::iterator_traits<InputIterator>::value_type
>::f(first,last);
};
Run Code Online (Sandbox Code Playgroud)
使用SFINAE,假设enable_if[_c]和is_same是无论是从升压或<type_traits>(和被适当地限定与任一boost::或std::分别地):
template<typename InputIterator>
typename enable_if<
!is_same<
typename std::iterator_traits<InputIterator>::value_type,
SomeSpecificType
>::value
>::type
f(InputIterator first, InputIterator last)
{
// Default implementation.
}
template<typename InputIterator>
typename enable_if<
is_same<
typename std::iterator_traits<InputIterator>::value_type,
SomeSpecificType
>::value
>::type
f(InputIterator first, InputIterator last)
{
// Special case
}
Run Code Online (Sandbox Code Playgroud)
在Boost案例中,使用boost::enable_if_c类似于上面的内容.你可以使用boost::enable_if和摆脱,::value但也必须使用例如boost::disable_if.