C++ 在子类中保存模板信息
我有一个带有函数的父类。在这个函数中,我想调用一个模板方法,但是模板的类型取决于子类的类型。所以我想把关于T的信息保存在那里。我不能用模板调用foo,因为它来自程序的另一部分,我无法更改C++ 在子类中保存模板信息,c++,templates,inheritance,C++,Templates,Inheritance,我有一个带有函数的父类。在这个函数中,我想调用一个模板方法,但是模板的类型取决于子类的类型。所以我想把关于T的信息保存在那里。我不能用模板调用foo,因为它来自程序的另一部分,我无法更改 class A { //this will be called on an instance of B or C, A will never be //instantiated void foo() { ba<T>(); } } clas
class A
{
//this will be called on an instance of B or C, A will never be
//instantiated
void foo()
{
ba<T>();
}
}
class B :public A
{
//T want to save here the Type of T so i won't have to call foo() with
//a template
}
class C :public A
{
//here comes another Type for T
}
A类
{
//这将在B或C的实例上调用,A将永远不会被调用
//实例化
void foo()
{
ba();
}
}
B类:公共A
{
//我不想在这里保存T的类型,这样就不必使用
//模板
}
C类:公共A类
{
//这是T的另一种类型
}
<代码> > p>您需要的是一个模式,这在C++模板编程中非常常见。
template<class T>
void ba() {}
template<class Derived>
struct A
{
void foo() {
ba<typename Derived::MyT>();
}
};
struct B
: public A<B>
{
using MyT = int;
};
struct C
: public A<C>
{
using MyT = double;
};
int main() {
B b;
b.foo();
C c;
c.foo();
}
模板
void ba(){}
模板
结构A
{
void foo(){
ba();
}
};
结构B
:公众A
{
使用MyT=int;
};
结构C
:公众A
{
使用MyT=double;
};
int main(){
B B;
b、 foo();
C C;
c、 foo();
}
您需要向基类a添加模板参数,然后在B和C声明中指定类型。请参见下面的示例:
template <typename T>
class A
{
public:
void foo()
{
ba<T>();
}
};
class B : public A<int>
{
};
class C : public A<bool>
{
};
int main()
{
B b;
C c;
b.foo(); // This calls ba<int>()
c.foo(); // This calls ba<bool>()
return 0;
}
模板
甲级
{
公众:
void foo()
{
ba();
}
};
B类:公共A
{
};
C类:公共A类
{
};
int main()
{
B B;
C C;
b、 foo();//这调用ba()
c、 foo();//这调用ba()
返回0;
}
花些时间来回顾一下模板和继承是如何工作的可能会更好
我不明白这里是什么。什么是“模板类型”?定义是模板T*ba(),例如我想用ba()调用B类中的foo(),我能把这方面的信息保存在B类中吗?你想像子类B
调用ba
,和C
调用ba
?是的,这就是我想要的,请先编辑你的问题,<代码>公共< /代码>不是资格类,C++不是java。