【发布时间】:2011-08-09 18:19:42
【问题描述】:
如何使用模板,在使用模板层时,如何找出类型是由哪些类型组成的?
让我们来
template <typename Super>
class A : public Super {};
template <typename Super>
class B : public Super {};
template <typename Super>
class C : public Super {};
class Blank{};
template <typename CombinedType>
void printTypeComponents(const CombinedType & t) { ... }
int main()
{
typedef A<B<C<Blank>>> ComposedType;
ComposedType ct;
printTypeComponents(ct);
typedef A<C<Blank>> ComposedType2;
ComposedType2 ct2;
printTypeComponents(ct2);
}
我附上了我的尝试,当然是错的(仅当对象由所有测试类型组成时才有效,因为测试类型确实存在),但您可以从中轻松看出我的目标是什么
#include <boost/type_traits/is_base_of.hpp>
#include <iostream>
template <typename Super>
class A : public Super
{
public:
typedef A<Super> AComponent;
};
template <typename Super>
class B : public Super
{
public:
typedef B<Super> BComponent;
};
template <typename Super>
class C : public Super
{
public:
typedef C<Super> CComponent;
};
class Blank{};
template <typename CombinedType>
void printTypeComponents(const CombinedType & t)
{
if(boost::is_base_of<Blank, CombinedType::AComponent>::value)
std::cout << "composed of A \n";
if(boost::is_base_of<Blank, CombinedType::BComponent>::value)
std::cout << "composed of B \n";
if(boost::is_base_of<Blank, CombinedType::CComponent>::value)
std::cout << "composed of C \n";
}
int main()
{
typedef A<B<C<Blank>>> ComposedType;
ComposedType ct;
printTypeComponents(ct);
//typedef A<C<Blank>> ComposedType2;
//ComposedType2 ct2;
//printTypeComponents(ct2);
}
我正在使用 MSVC2010
谢谢!
编辑: 我实际上对类型的名称并不感兴趣......我想像这样使用它:
if(composedOfA)
doSomeCharacteristicStuffFromA(); //member function of A
if(composedOfB)
doSomeCharacteristicStuffFromB(); //member function of B
【问题讨论】:
-
@relax - 或虚函数...
标签: c++ templates c++11 metaprogramming typetraits