我想向两个现有的 C++ 类添加交换功能。一个类继承自另一个类。我希望每个类的实例只能与同一类的实例交换。为了使其半具体化,假设我有 Foo 和 Bar 类。Bar 继承自 Foo。我定义了 Foo::swap(Foo&) 和 Bar::swap(Bar&)。Bar::swap 代表 Foo::swap。我希望 Foo::swap 仅适用于 Foo 实例,而 Bar::swap 仅适用于 Bar 实例:我不知道如何强制执行此要求。
这是给我带来麻烦的示例:
#include <algorithm>
#include <iostream>
struct Foo {
int x;
Foo(int x) : x(x) {};
virtual void swap(Foo &other) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
std::swap(this->x, other.x);
};
};
struct Bar : public Foo {
int y;
Bar(int x, int y) : Foo(x), y(y) {};
virtual void swap(Bar &other) {
std::cout << __PRETTY_FUNCTION__ << " ";
Foo::swap(other);
std::swap(this->y, other.y);
};
};
void display(Foo &f1, Foo &f2, Bar &b34, Bar &b56)
{
using namespace std;
cout << "f1: " << f1.x << endl;
cout << "f2: " << f2.x << endl;
cout << "b34: " << b34.x << " " << b34.y << endl;
cout << "b56: " << b56.x << " " << b56.y << endl;
}
int main(int argc, char **argv)
{
{
Foo f1(1), f2(2);
Bar b34(3,4), b56(5,6);
std::cout << std::endl << "Initial values: " << std::endl;
display(f1,f2,b34,b56);
}
{
Foo f1(1), f2(2);
Bar b34(3,4), b56(5,6);
std::cout << std::endl << "After Homogeneous Swap: " << std::endl;
f1.swap(f2); // Desired
b34.swap(b56); // Desired
display(f1,f2,b34,b56);
}
{
Foo f1(1), f2(2);
Bar b34(3,4), b56(5,6);
std::cout << std::endl << "After Heterogeneous Member Swap: " << std::endl;
// b56.swap(f2); // Doesn't compile, excellent
f1.swap(b34); // Want this to not compile, but unsure how
display(f1,f2,b34,b56);
}
return 0;
}
这是输出:
Initial values:
f1: 1
f2: 2
b34: 3 4
b56: 5 6
After Homogeneous Swap:
virtual void Foo::swap(Foo&)
virtual void Bar::swap(Bar&) virtual void Foo::swap(Foo&)
f1: 2
f2: 1
b34: 5 6
b56: 3 4
After Heterogeneous Member Swap:
virtual void Foo::swap(Foo&)
f1: 3
f2: 2
b34: 1 4
b56: 5 6
您可以在最终输出组中看到 f1.swap(b34) 以一种可能令人讨厌的方式“切片” b34。我希望有罪的行在运行时不编译或炸毁。由于涉及到继承,如果我使用非成员或朋友交换实现,我想我会遇到同样的问题。
如果有帮助,该代码可在键盘上找到。
出现此用例是因为我想将交换添加到 boost::multi_array 和 boost::multi_array_ref。multi_array 继承自 multi_array_ref。只有将 multi_arrays 与 multi_arrays 交换,将 multi_array_refs 与 multi_array_refs 交换才有意义。