是否可以从模板类型自动获取基类的类型? [英] Can the type of a base class be obtained from a template type automatically?
本文介绍了是否可以从模板类型自动获取基类的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用模板元程序来确定基类。有没有办法自动获取基类而不明确专门为每个派生类?
class foo {public:char * Name (){returnfoo; }; };
类bar:public foo {public:char * Name(){returnbar; }; };
template<类型名T> struct ClassInfo {typedef T Base; };
模板<> struct ClassInfo< bar> {typedef foo Base; };
int main()
{
ClassInfo< foo> :: Base A;
ClassInfo< bar> :: Base B;
std :: cout<<一个名字(); // foo
std :: cout<< B.Name(); // foo
}
现在任何自动方法都需要选择第一个声明
解决方案
我的解决方案并不是真正的自动,而是我能想到的最好的。 p>
Intrusive C ++ 03解决方案:
class B {};
A类:public B
{
public:
typedef B Base;
};
非侵入式C ++ 03解决方案:
class B {};
A类:public B {};
template< class T>
struct TypeInfo;
模板<>
struct TypeInfo< A>
{
typedef B Base;
};
I am trying to use template meta-programming to determine the base class. Is there a way to get the base class automatically without explicitly specializing for each derived class?
class foo { public: char * Name() { return "foo"; }; };
class bar : public foo { public: char * Name() { return "bar"; }; };
template< typename T > struct ClassInfo { typedef T Base; };
template<> struct ClassInfo<bar> { typedef foo Base; };
int main()
{
ClassInfo<foo>::Base A;
ClassInfo<bar>::Base B;
std::cout << A.Name(); //foo
std::cout << B.Name(); //foo
}
for right now any automatic method would need to select the first declared base and would fail for private bases.
解决方案
My solutions are not really automatic, but the best I can think of.
Intrusive C++03 solution:
class B {};
class A : public B
{
public:
typedef B Base;
};
Non-intrusive C++03 solution:
class B {};
class A : public B {};
template<class T>
struct TypeInfo;
template<>
struct TypeInfo<A>
{
typedef B Base;
};
这篇关于是否可以从模板类型自动获取基类的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文