Lim*_*hin 12 c++ variadic-templates c++11
我正在尝试交换参数包的两个项目.
理想情况下,我想做这样的事情:
template<int i1, int i2, class... Args>
void swapped_copy(some_class a, some_class b, Args... args) {
a(args...) = b(/* 'args...' where parameters with indices i1 and i2 are swapped */);
}
Run Code Online (Sandbox Code Playgroud)
任何的想法?
非常感谢.
您可以使用a std::tuple来打包args并通过索引解压缩,然后使用a std::index_sequence来生成要使用的索引.那么这只是在索引上进行交换的问题.像这样的东西:
namespace swapped_copy_detail {
constexpr std::size_t swap_one_index(
std::size_t i1, std::size_t i2, std::size_t index) {
return index==i1 ? i2 : (index==i2 ? i1 : index);
}
template <std::size_t i1, std::size_t i2, class Tuple, std::size_t... Inds>
void do_swapped_copy(
some_class& a, some_class& b,
Tuple&& args,
std::index_sequence<Inds...> inds ) {
a(std::get<Inds>(args)...) =
b(std::get<swap_one_index(i1, i2, Inds)>(args)...);
}
}
template <std::size_t i1, std::size_t i2, class ...Args>
void swapped_copy(some_class a, some_class b, const Args& ...args) {
static_assert(i1 < sizeof...(Args) && i2 < sizeof...(Args),
"Index too large for swapped_copy");
swapped_copy_detail::do_swapped_copy<i1, i2>(
a, b, std::tie(args...),
std::index_sequence_for<Args...>());
}
Run Code Online (Sandbox Code Playgroud)
index_sequence并且index_sequence_for在C++ 14标准中,但您的问题被标记为[c ++ 11].如果您需要坚持使用C++ 11,可以在这个答案中找到这些实用程序的实现.