我正在尝试将复制和交换习语放入可重用的混合中:
template<typename Derived>
struct copy_and_swap
{
Derived& operator=(Derived copy)
{
Derived* derived = static_cast<Derived*>(this);
derived->swap(copy);
return *derived;
}
};
我打算通过 CRTP 将其混合:
struct Foo : copy_and_swap<Foo>
{
Foo()
{
std::cout << "default\n";
}
Foo(const Foo& other)
{
std::cout << "copy\n";
}
void swap(Foo& other)
{
std::cout << "swap\n";
}
};
但是,一个简单的测试表明它不起作用:
Foo x;
Foo y;
x = y;
这只会打印两次“default”,既不打印“copy”也不打印“swap”。我在这里想念什么?