从const派生的类的模板问题

template issue with class derived from const

本文关键字:问题 派生 const      更新时间:2023-10-16

给定以下代码:

class MyClass {};
template< class T > class Base {};
template< class T > class Derived : public Base< const T > {};
Base< const MyClass* >* MyFunc ()
{
    return new Derived< MyClass* >();
}

clang给出:

error: cannot initialize return object of type 'Base<const MyClass *> *' with an rvalue of type 'Derived<MyClass *> *'

但是,"Derived MyClass*"是从"Base const MyClass*"派生而来的,所以我希望它能工作。我做错了什么?

这是因为Derived<MyClass*>派生自Base<MyClass* const>,而不是Base<const MyClass*>。前者表示指向MyClassconst指针,后者表示指向const MyClass的指针。

你需要考虑你想要成为const:指针还是指针对象。

如果是指针,那么只需将返回类型更改为Base<MyClass* const>*。

如果它是指针对象,那么您需要在Derived的定义中对T进行一些转换。如果您只希望T是一个指针,那么const std::remove_pointer_t<T>*可能对您有效,否则您将需要进行一些部分专门化。

Derived< MyClass* >源自Base<MyClass * const>
注意这里的const是什么,因为T不是MyClass,而是MyClass*

如果要在T是指针类型时强制将const应用于指针对象,则需要使用辅助模板&一些元编程。

混淆的来源:

const MyClass* ptr;  // ptr is is a non-const pointer to a const object
MyClass* const ptr;  // ptr is a const pointer to a non-const object.

因此,您需要使用:

Base< MyClass const* >* MyFunc ()
{
    return new Derived< MyClass* >();
}