为什么将好奇模板模式的基类直接转换为另一个基类是错误的?



我正在学习好奇的模板模式(crpt模式)。 我想减少具有 crtp 模式的类中的重复代码。 以下示例的要点是

  1. C 类是容器的维护者,类 Container<(int)> 和 Container<(double)>

  2. 类 C 提供了一种访问上述容器的方法。

  3. 访问容器的函数使用 crtp 模式实现为 GET_CONTAINRE_CRTP<(C)>。

以下代码运行良好。但是如果我改变它不起作用 GET_CONTAINRE_CRTP::container_pair() 中案例 2 到案例 1 的代码;对我来说,案例 1 和案例 2 的代码是等效的。

为什么案例 1 的代码无法将 crtp 的基类转换为另一个基类? 而且,我想澄清一下案例 2 的代码在 c++ 法规中是否有效,它提供了一种访问另一个基类的方法。

谢谢。

法典:

template <typename T>
class Container : public std::vector<T> {};
template <typename Derived>
class GET_CONTAINRE_CRTP {
public:
template <typename T>
auto& container_pair(void) {
// case 1: error at compiling
// return static_cast<typename Derived::template ContianerChoice<T>&>(*this);
// case 2: works well
Derived* host = static_cast<Derived*>(this);
return static_cast<typename Derived::template ContianerChoice<T>&>(*host);
}
};
class C : private Container<int>, private Container<double>, public GET_CONTAINRE_CRTP<C> {
public:
template <typename T>
using ContianerChoice = Container<T>;
C(void) {
this->Container<int>::push_back(1);
this->Container<double>::push_back(3);
}
friend class GET_CONTAINRE_CRTP<C>;
};

void test_get_container_by_crtp(void) {
C c{};
auto& container_int = c.container_pair<int>();
std::cout << "value of contianer int at index 0 = " << container_int[0] << "." << std::endl;
auto& container_double = c.container_pair<double>();
std::cout << "value of contianer double at index 0 = " << container_double[0] << "." << std::endl;
}

上述执行结果test_get_container_by_crtp() :

value of contianer int at index 0 = 1.
value of contianer double at index 0 = 3.

为了提炼出你的问题,你实际上是在问为什么以下方法不起作用:

struct base_a {};
struct base_b {};
struct derived : base_a, base_b {};
derived d;
base_a& a = d;
base_b& b = static_cast<base_b&>(a); // error: cannot cast from `base_a&` to `base_b&`

引用 cpp首选项,给定表达式static_cast<new_type>(expression)

如果new_type是指向某个类D的指针或引用,而expression的类型是指向其非虚拟基B的指针或引用,则static_cast执行向下转换

你正在尝试做等价的static_cast<base_b&>(a),并且由于base_a不是base_b的非虚拟基类,这不是一个有效的下沉。相反,您需要向下转换为derived&然后隐式转换为base_b&

base_b& b = static_cast<derived&>(a);

或者在您的情况下:

template <typename T>
auto& container_pair(void) {
using Choice = typename Derived::template ContianerChoice<T>;
Choice& c = static_cast<Derived&>(*this);
return c;
}

为什么案例 1 的代码无法将 crtp 的基类转换为另一个基类?

这就是static_cast的工作方式。Container<To>既不是派生类也不是GET_CONTAINRE_CRTP<C>的基类,所以你不能使用static_cast在它们之间转换。
无论如何,碰巧Container<To>C的基类,因此您可以使用static_castGET_CONTAINRE_CRTP<C>转换为其派生类C然后将其强制转换为所需的容器(即另一个子类)。
否则,您可以使用reinterpret_cast一次完成工作。

最新更新