C++模板判断函数是否被定义
#include "stdafx.h"
#include <iostream>
using namespace std;
struct abc
{
int i;
abc(int ii):i(ii){}
unsigned GetUnsignedHash(void);
};
unsigned abc::GetUnsignedHash(void)
{
return i;
}
template<class T>
class testclass
{
public:
T testabc;
bool testFun(void);
testclass(void);
~testclass(void);
};
template<class T>
testclass<T>::testclass(void):testabc(2)
{}
template<class T>
testclass<T>::~testclass(void)
{}
template<class T>
bool testclass<T>::testFun(void)
{
#if T::GetUnsignedHash > 0 //怎么判断GetUnsignedHash有没有被定义
return true;
#else
return false;
#endif
}
int main(int argc, char* argv[])
{
testclass<abc> ji;
cout<<ji.testFun()<<endl;
return 0;
}
//那个#if 后面不管填什么,testFun()都是返回 false,有没有什么方法改,请高手指教,
//就是判断 T::GetUnsignedHash 有没有被定义,而进行选择性编译
//希望能给出修改的方法,vc.net 2003 编译器
问题点数:20、回复次数:5Top
1 楼iamwindywolf(疾风之狼)回复于 2005-08-02 19:58:20 得分 5
不妨在定义这个函数的时候就#define一个宏,然后判断#ifdef就可以了啊.Top
2 楼021850524(吸血鬼牌卫生巾)回复于 2005-08-02 21:41:10 得分 5
//这样可以吗?
#include "stdafx.h"
#include <iostream>
using namespace std;
struct abc
{
int i;
abc(int ii):i(ii){}
#ifndef GET_UNSIGNED_HASH // 宏GET_UNSIGNED_HASH表示此函数已经在别的地方定义过了.
unsigned GetUnsignedHash(void);
#endif
};
unsigned abc::GetUnsignedHash(void)
{
return i;
}
template<class T>
class testclass
{
public:
T testabc;
bool testFun(void);
testclass(void);
~testclass(void);
};
template<class T>
testclass<T>::testclass(void):testabc(2)
{}
template<class T>
testclass<T>::~testclass(void)
{}
template<class T>
bool testclass<T>::testFun(void)
{
/*
#if T::GetUnsignedHash > 0 //怎么判断GetUnsignedHash有没有被定义
return true;
#else
return false;
#endif
*/
#if !defined GET_UNSIGNED_HASH
return true;
#else
return false;
#endif
}
// 然后你就可以在你的编译器里决定是否编译宏包围的这段了.
int main(int argc, char* argv[])
{
testclass<abc> ji;
cout<<ji.testFun()<<endl;
return 0;
}
Top
3 楼vvvvy()回复于 2005-08-02 22:02:58 得分 0
int main(int argc, char* argv[])
{
testclass<abc> ji;
testclass<int> jint;
cout<<ji.testFun()<<endl;
cout<<jint.testFun()<<endl;
return 0;
}
上面的我也想过,但不是我想要的,因为有的并没有定义那个函数,
如上面的 jint.testFun() 我要的返回 falseTop
4 楼mdj_boy(春秋文武)回复于 2005-08-03 09:29:46 得分 5
mark...Top
5 楼xuanwenchao(xuanwenchao)回复于 2005-08-03 09:51:38 得分 5
我也想知道,帮你顶顶顶!!!Top




