您可以使用 std::tuple 来打包 args 并按索引解包,并使用 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...>());
}
index_sequence 和 index_sequence_for 在 C++14 标准中,但您的问题被标记为 [c++11]。如果您需要坚持使用 C++11,可以在 this answer 中找到这些实用程序的实现。