请教编译期如何识别类型
template<bool> class test{};
int main(int argc, char* argv[])
{
test< ( 取得类名(int) == 取得类名(char) ) >();
return 0;
}
编译期判别两个类名,请问如何判别,谢谢
问题点数:50、回复次数:12Top
1 楼qhfu(改个名字)回复于 2005-06-02 21:11:20 得分 5
用typeid(int).name() 可以吗?Top
2 楼gzxb(老白)回复于 2005-06-02 21:19:49 得分 0
不行,typeid好像是执行期的
i:\temp\console\console.cpp(37) : error C2973: 'test1' : invalid template argument '__formal'
i:\temp\console\console.cpp(37) : see declaration of 'test1'
i:\temp\console\console.cpp(41) : see reference to class template instantiation 'test1< ?? >' being compiledTop
3 楼mostideal(三甲)回复于 2005-06-02 21:41:53 得分 0
我不知道,,帮顶。。Top
4 楼ddc(ddc)回复于 2005-06-02 21:44:05 得分 40
template<class T,class U>
class Conv
{
public: enum{same=false};
};
template<class T> //特化一个相同类型的
class Conv<T,T>
{
public: enum{same=true};
};
int main(int argc, char* argv[])
{
bool isSame = Conv<int,char>::same;
return 0;
}
Top
5 楼gzxb(老白)回复于 2005-06-02 21:51:56 得分 0
ddc(ddc) 您好,不好意思请教一下,我用的是VC6,好像VC6不支持模板偏特化吧?
Top
6 楼gzxb(老白)回复于 2005-06-02 21:58:30 得分 0
在vc6下有什么好办法?Top
7 楼sinkinglife(沉沦)回复于 2005-06-02 22:13:58 得分 0
没有明白楼主的意思。Top
8 楼lfeiman888(feiman)回复于 2005-06-02 22:15:05 得分 5
贴段代码,不知道对你有没有作用.从新闻组里面得到的
//运行时类型识别
//利用curiously recurring template pattern" + extracting
//typesafe bits int a base class
#include <iostream>
using namespace std;
class Data{};
class DataTypeA:public Data{};
class DataTypeB:public Data{};
class Base{
public:
virtual Data* LookupData() = 0;
};
//接口类
template<typename DataType>
class Derived:public Base{
public:
virtual DataType *LookupData() = 0;
virtual void ProcessData(DataType*) = 0;
};
//接受A类型参数类
class DerivedTypeA:public Derived<DataTypeA>{
public:
DataTypeA *LookupData()
{
return 0;
}
void ProcessData(DataTypeA *pData) {}
};
//接受B类型参数类
class DerivedTypeB:public Derived<DataTypeB>{
public:
DataTypeB * LookupData()
{
return 0;
}
void ProcessData(DataTypeB *pData){}
};
int main()
{
DerivedTypeA *pA = new DerivedTypeA;
DerivedTypeB *pB = new DerivedTypeB;
DataTypeA * pData = pA->LookupData();
//以下语句编译时出错
// pB->ProcessData(pData);
return 0;
}
Top
9 楼zdy_8212(zdy_8212)回复于 2005-06-03 01:40:31 得分 0
上面的码挺不错了,没细看,呵。。楼主的意思有点不大明白。Top
10 楼gzxb(老白)回复于 2005-06-05 12:11:47 得分 0
不好意思各位,可能我写得不够清楚。
我就是要实现5楼 ddc(ddc) 那段代码要实现的功能,不过VC6不支持模板偏特化,所以那段不能在VC6中编译,想请教还有什么能在VC6中实现得办法Top
11 楼gzxb(老白)回复于 2005-06-05 14:36:55 得分 0
我想到一个办法,不过稍微麻烦一点点
template<class T1, class T2>
struct is_same_type
{
template<class T>
struct check_type{
enum{ is_same = 0 };
};
template<>
struct check_type<T1>{
enum{ is_same = 1 };
};
};
#define MYTL_IS_SAME_TYPE(TYPE1, TYPE2) mytl::is_same_type<TYPE1, TYPE2>::check_type<TYPE2>::is_same
Top
12 楼gzxb(老白)回复于 2005-06-05 14:38:02 得分 0
这样在VC6下就能用了,唉~~~VC6还真垃圾,搞得这么麻烦Top




