操作可变函数模板的函数参数
Manipulate function arguments of a variadic function template
我有一对 begin()
/end()
方法声明如下:
template <typename... Ts>
Iterator begin(Ts... indices) const;
template <typename... Ts>
Iterator end(Ts... indices) const;
从逻辑上讲,end()
可以用begin()
来实现。具体来说,end(x, y, ..., z)
等同于 begin(x, y, ..., z + 1)
。那么,有没有一种干净的方法可以使用 indices
将 x, y, ..., z
变成 x, y, ..., z + 1
,这样我就可以像
一样实现 end()
template <typename... Ts>
Iterator end(Ts... indices) const {
return begin(whatever to do with indices...);
}
template <std::size_t...Is,class... Ts>
Iterator end_impl(std::index_sequence<Is...>,Ts... indices) const{
auto tup=std::tie(indices...);
return begin(std::get<Is>(tup)..., std::get<sizeof...(Ts)-1>(tup)+1);
}
template <class... Ts>
Iterator end(Ts... indices) const{
return end_impl(std::make_index_sequence<sizeof...(Ts)-1>{}, indices...);
}
加点完美转发和隐私就可以了
使用 C++14,但实现部分相对容易。
我有一对 begin()
/end()
方法声明如下:
template <typename... Ts>
Iterator begin(Ts... indices) const;
template <typename... Ts>
Iterator end(Ts... indices) const;
从逻辑上讲,end()
可以用begin()
来实现。具体来说,end(x, y, ..., z)
等同于 begin(x, y, ..., z + 1)
。那么,有没有一种干净的方法可以使用 indices
将 x, y, ..., z
变成 x, y, ..., z + 1
,这样我就可以像
end()
template <typename... Ts>
Iterator end(Ts... indices) const {
return begin(whatever to do with indices...);
}
template <std::size_t...Is,class... Ts>
Iterator end_impl(std::index_sequence<Is...>,Ts... indices) const{
auto tup=std::tie(indices...);
return begin(std::get<Is>(tup)..., std::get<sizeof...(Ts)-1>(tup)+1);
}
template <class... Ts>
Iterator end(Ts... indices) const{
return end_impl(std::make_index_sequence<sizeof...(Ts)-1>{}, indices...);
}
加点完美转发和隐私就可以了
使用 C++14,但实现部分相对容易。