从const派生的类的模板问题
template issue with class derived from const
给定以下代码:
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*>
。前者表示指向MyClass
的const
指针,后者表示指向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* >();
}
相关文章:
- 从基指针到派生的强制转换问题
- 关于C++从派生类调用在基类中实现的虚拟函数的问题
- SIGSEGV 因为基/派生类的继承问题
- C 两个派生的类中有彼此的对象(包括问题)
- 使用 boost::序列化将派生类指针序列化为向量时出现问题
- 类型特征检查 CRTP 派生,在基类中,问题是未定义的类型
- 有关通过派生类在命名空间内继承的问题
- 如果私有虚拟函数被覆盖为派生类中的公共函数,那么问题是什么
- 分配派生类的对象时出现问题,其中基类具有抽象虚函数
- 覆盖派生类的函数时遇到问题
- 派生类中的模板存在问题
- 使用基对象修改/访问派生类的信息的有问题的设计
- 设计问题迫使我将基类向下转换为派生类型
- 从嵌套在模板中的类派生时编译问题
- 从派生类调用基类函数时出现问题
- 派生类问题中的C++继承默认构造函数
- 如何解决具有多个派生类的抽象基类的继承问题
- 使用Boost:serialize反序列化指向派生类的指针时出现问题
- c++派生类构造函数问题
- 继承的问题:派生类不继承基类