使用 reinterpret_cast 和 static_cast 模拟具有多态参数的模板中的协变和逆变?

Simulating covariance and contravariance in templates with polymorphic parameters using reinterpret_cast and static_cast?

假设我有一个简单的多态继承:

struct Base
{
    virtual void exec() { std::cout << "base" << std::endl; }
    virtual ~Base() { }
};

struct Derived1 : public Base
{
    void exec() override { std::cout << "derived1" <<std::endl; }
};

struct Derived2 : public Base
{
    void exec() override { std::cout << "derived2" << std::endl; }
};

我还有一个模板 Wrapper class 可以存储一些通用数据:

template<typename T> struct Wrapper : public T
{
    bool b{true};     
};

我可以使用以下转换安全地从 Wrapper<Derived1> 转换为 Base 以及从 Base 转换为 Wrapper<Derived1> 吗?

template<typename T> auto& asWrapper(T& mX) 
{ 
    return static_cast<Wrapper<T>&>(mX); 
}

template<typename T, typename TWrapper> auto& asT(TWrapper& mX) 
{ 
    return reinterpret_cast<T&>(mX); 
}

似乎可行的示例:

int main()
{
    auto d1 = std::make_unique<Wrapper<Derived1>>();
    auto d2 = std::make_unique<Wrapper<Derived2>>();

    Base* bd1 = d1.get();
    Base* bd2 = d2.get();

    bd1->exec();
    bd2->exec();

    auto& bl1 = asWrapper(*bd1);
    auto& bl2 = asWrapper(*bd2);

    std::cout << bl1.b << " " << bl2.b << std::endl;
    bl1.b = false;
    std::cout << bl1.b << " " << bl2.b << std::endl;
    bl2.b = false;
    std::cout << bl1.b << " " << bl2.b << std::endl;

    asT<Derived1>(bl1).exec();
    asT<Derived2>(bl2).exec();

    return 0;
}

可执行示例:http://ideone.com/MRy9Hy


这似乎可行,但我不确定这种方法的安全性。它符合标准吗?它会导致未定义的行为吗?

包装器

N4140 [expr.static.cast]/2:

An lvalue of type “cv1 B,” where B is a class type, can be cast to type “reference to cv2 D,” where D is a class derived (Clause 10) from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is neither a virtual base class of D nor a base class of a virtual base class of D. The result has type “cv2 D.” An xvalue of type “cv1 B” may be cast to type “rvalue reference to cv2 D” with the same constraints as for an lvalue of type “cv1 B.” If the object of type “cv1 B” is actually a subobject of an object of type D, the result refers to the enclosing object of type D. Otherwise, the behavior is undefined.

所以你的函数 aswrapper 只有在传递给它的 T& 实际引用 Wrapper<T>T 基础对象时才定义行为。示例程序中的两个调用都将 Base& 转换为 Wrapper<Base>&,但两个参数实际上都不是 Wrapper<Base>& 的基对象,因此结果行为未定义。

asT

[expr.reinterpret.cast]:

...

7 An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of object pointer type is converted to the object pointer type “pointer to cv T”, the result is static_cast<cv T*>(static_cast<cv void*>(v)). Converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value.

...

11 A glvalue expression of type T1 can be cast to the type “reference to T2” if an expression of type “pointer to T1” can be explicitly converted to the type “pointer to T2” using a reinterpret_cast. The result refers to the same object as the source glvalue, but with the specified type. [ Note: That is, for lvalues, a reference cast reinterpret_cast<T&>(x) has the same effect as the conversion *reinterpret_cast<T*>(&x) with the built-in & and * operators (and similarly for reinterpret_cast<T&&>(x)). —end note ] No temporary is created, no copy is made, and constructors (12.1) or conversion functions (12.3) are not called.

所以 asT<T>(WrapperT& foo) 等价于 *reinterpret_cast<T*>(&foo) 等价于 *static_cast<T*>(static_cast<void*>(&foo))。指向 Wrapper<Base> 的指针当然可以根据 [expr.static.cast]/4:

转换为 void*

An expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The expression e is used as a glvalue if and only if the initialization uses it as a glvalue.

因为任何指针类型隐式转换为 void* 每个 [conv.ptr]/2:

A prvalue of type “pointer to cv T,” where T is an object type, can be converted to a prvalue of type “pointer to cv void”. The result of converting a non-null pointer value of a pointer to object type to a “pointer to cv void” represents the address of the same byte in memory as the original pointer value. The null pointer value is converted to the null pointer value of the destination type.

void*可以通过[expr.static.cast]/13:

转换为任何对象指针类型

A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to *cv*2 T,” where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. The null pointer value is converted to the null pointer value of the destination type. If the original pointer value represents the address A of a byte in memory and A satisfies the alignment requirement of T, then the resulting pointer value represents the same address as the original pointer value, that is, A. The result of any other such pointer conversion is unspecified. A value of type pointer to object converted to “pointer to cv void” and back, possibly with different cv-qualification, shall have its original value.

考虑到上面的 asT 是格式正确的——你已经知道了,因为编译器没有诊断它。但是,示例程序中的两个调用具有未指定的行为,因为 Wrapper<Base> 的对齐可能不满足 Derived1Derived2 的对齐要求。即使满足对齐要求 ,对 exec 的调用也很可能与 3.10/10 中的严格别名限制发生冲突,因为您正在处理可能是对象表示的内容一个 Wrapper<Base> 就好像它是一个 Derived.

按原样用reinterpret_cast编写,asT<Base>(Wrapper<Base>&)甚至有未定义的行为。当然对齐要求得到满足,因为 Wrapper<Base> 派生自 Base,但实际上使用返回的泛左值访问内存只有在 Wrapper<Base> 的地址与它的 Base 子对象。如果 Wrapper<Base> 是标准布局,就会出现这种情况,否则对象布局未指定。

总结

该程序多次出现未定义的行为。正常工作的外观是实施选择的对象布局的产物。