在我所理解的所有语言中,这是不可能的,但是有人告诉我在C++中这是可能的,但我很难相信它。从本质上讲,当你参数化一个类时,你在编译阶段创建了一个唯一的类,不是吗?
如果我的问题不清楚,请告诉我。
这里是我试图解释我正在尝试做的事情(注意L类):
//; g++ ModifingBaseClassParameter.cpp -o ModifingBaseClassParameter;ModifingBaseClassParameter
#include <iostream>
using namespace std;
template<typename T>
class Base
{
public:
Base() {}
Base(T& t) : m_t(t) {}
T& getMem() {return m_t;}
private:
T m_t;
};
template<typename T>
class F: Base<T>
{};
template<typename T>
class L: F<long>
{};
int main()
{
Base<int> i;
F<float> f;
L<long> l;
cout<<i.getMem()<<endl;
// cout<<f.getMem()<<endl; // why doesn't this work
// cout<<l.getMem()<<endl; // why doesn't this work
}所以正如你所看到的(希望我的语法是有意义的),类L正试图将它的父类的float参数重新定义为long类型。这看起来当然不合法,但我会与专家们意见不同。
发布于 2010-01-06 05:48:47
如果你想问你是否可以在c++中做到这一点:
template <>
class ParamClass<Type1> : public ParamClass<Type2>
{
};那么,是的,这是可能的。
它经常被用来定义模板列表或从另一种类型继承特征。
发布于 2010-01-06 07:35:42
您所要求的内容不能直接完成--但您可以通过使用默认模板参数来实现:
template <typename T>
class Base { };
template <typename T = int>
class X : Base<T> {};
class Y : Base<float>
class Z : X<long> {};在这种情况下,默认模板参数不会添加太多内容。您必须提供模板参数列表来实例化模板,即使所有参数都提供了默认值。因此,在派生类中重写的默认值通常只对第二个和后续参数有用。
发布于 2012-05-15 15:29:51
#include <iostream>
#include <typeinfo>
using namespace std;
template<typename T>
class Base
{
public:
Base() {}
Base(T& t) : m_t(t) {}
T& getMem() {return m_t;}
private:
T m_t;
};
template<typename T>
class F: public Base<T>
{};
template<typename T>
class L: public F<long>
{};
int main()
{
Base<int> iNTEGER;
F<float> fLOAT;
L<long> lONG;
int x;
cout << typeid(iNTEGER.getMem()).name() << endl;
cout << typeid(fLOAT.getMem()).name() <<endl; // this works now :)
cout << typeid(lONG.getMem()).name() <<endl; // this works now :)
}默认情况下,继承在c++中是私有的,一旦公开了,除非你想问其他东西,否则stephenmm写的应该是什么?
https://stackoverflow.com/questions/2009295
复制相似问题