두 개의 기존 C++ 클래스에 스왑 기능을 추가하고 싶습니다. 한 클래스는 다른 클래스로부터 상속받습니다. 각 클래스의 인스턴스를 같은 클래스의 인스턴스로만 교체 할 수 있기를 바랍니다. 반 콘크리트로 만들려면 Foo and Bar 클래스가 있다고 말하십시오. Bar는 Foo를 상속합니다. 나는 Foo :: swap (Foo &)과 Bar :: swap (Bar &)을 정의한다. Bar :: 대리인을 Foo :: Swap에 스왑합니다. 나는 Foo :: Foo 인스턴스와 Bar :: swap 만 Bar 인스턴스에서 작업하도록 바꾸기를 원합니다.이 요구 사항을 적용하는 방법을 파악할 수 없습니다. 출력 여기상속 시나리오에서의 C++ 스왑 문제
#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 여기
나에게 문제를주고 있는지의 샘플입니다 잠재적으로 불쾌한 방법으로 유죄 선을 런타임에 컴파일하거나 분해하지 말아야합니다. 상속 때문에, 비회원 또는 친구 스왑 구현을 사용하면 같은 문제가 발생한다고 생각합니다.이 코드는 도움이 될 경우 codepad에 있습니다.
이 사용 사례는 I want to add swap to boost::multi_array and boost::multi_array_ref이므로 발생합니다. multi_array는 multi_array_ref에서 상속됩니다. multi_array와 multi_array_refs를 multi_array_refs로 바꾸는 것만으로도 의미가 있습니다.
분명히 못 생겼지 만 이것이 실제로 실용 가능한 유일한 것 같아요. 감사합니다 더글러스. –