gpt4 book ai didi

c++ - 基于策略的类中的策略转换运算符与私有(private)析构函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:21:33 25 4
gpt4 key购买 nike

Modern C++ Design: Generic Programming and Design Patterns Applied 中,Andrei Alexandrescu 提倡保护策略的析构函数:

Because the destructor is protected, only derived classes can destroy policy objects, so it's impossible for outsiders to apply delete to a pointer to a policy class. The destructor, however, is not virtual, so there is no size or speed overhead

但后来,他写了以下关于政策兼容性的段落:

As you can see, you have two-sided flexibility in implementing conversions between policies. You can implement a conversion constructor on the left-hand side, or you can implement a conversion operator on the right-hand side.

假设我们有 2 个策略:

class First{
public:
First() = default;
First(const First&) = default;

protected:
~First() = default;
};

class Second{
public:

explicit operator First() const {
return //what???
}

Second() = default;
Second(const Second&) = default;
Second(const First& ) {};

protected:
~Second() = default;
};

如何在不构造 First 类型的临时对象的情况下创建从策略 Second 到策略 First 的转换运算符?

最佳答案

问题是你不能用 protected 析构函数创建对象,派生类除外。因此禁止创建此类临时对象的转换运算符。解决它的一种方法是制作 FirstSecond通过explicit互相接受构造函数:

#include <iostream>

class First;
class Second;

class First
{
public:
First() = default;
First(const First&) = default;
explicit First(const Second&);
int value() const { return x; }
protected:
~First() = default;
private:
int x = 1;
};

class Second
{
public:
Second() = default;
Second(const Second&) = default;
explicit Second(const First&);
int value() const { return x; }
protected:
~Second() = default;
private:
int x = 2;
};

First::First(const Second& s): x(s.value()) {}
Second::Second(const First& f): x(f.value()) {}

然后您可以创建一个主机类模板Host<Policy>具有转换策略的模板化转换构造函数 Policy和任意 U

template<class Policy>
class Host
:
public Policy
{
public:
Host() = default;

template<class U>
Host(Host<U> const& other)
:
Policy(other)
{}
};

int main()
{
Host<First> h1;
Host<Second> h2;
Host<Second> h3(h1);
Host<First> h4(h2);

std::cout << h1.value() << "\n";
std::cout << h2.value() << "\n";
std::cout << h3.value() << "\n";
std::cout << h4.value() << "\n";
}

Live Example .

请注意,确实推荐使用 protected 析构函数和公共(public)继承,但特别推荐它们以安全地使用“丰富的”(即有状态的)策略。对于无状态策略,还可以使用 protected 继承和公共(public)析构函数。对于这些策略,转换运算符可以很好地生成临时变量。

关于c++ - 基于策略的类中的策略转换运算符与私有(private)析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25504264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com