模板参数检查是否有一个成员函数
问题描述:
Possible Duplicate:
Is it possible to write a C++ template to check for a function's existence?模板参数检查是否有一个成员函数
这是非常相似,我earlier question。我想检查一个模板参数是否包含成员函数。
我试过这段代码,与我在前一个问题中接受的答案类似。
struct A
{
int member_func();
};
struct B
{
};
template<typename T>
struct has_member_func
{
template<typename C> static char func(???); //what should I put in place of '???'
template<typename C> static int func(...);
enum{val = sizeof(func<T>(0)) == 1};
};
int main()
{
std::cout<< has_member_func<B>::val; //should output 0
std::cout<< has_member_func<A>::val; //should output 1
}
但我不知道应该用什么来代替???
才能使它工作。 我是SFINAE概念的新手。
答
的MSalters'的想法稍加修改从Is it possible to write a C++ template to check for a functions existence?:类似
template<typename T>
class has_member_func
{
typedef char no;
typedef char yes[2];
template<class C> static yes& test(char (*)[sizeof(&C::member_func)]);
template<class C> static no& test(...);
public:
enum{value = sizeof(test<T>(0)) == sizeof(yes&)};
};
使用的东西HAS_MEM_FUNC这约翰内斯张贴在该线程。我以前使用过这个代码,它工作正常。 – 2010-12-04 14:18:49
icecrime感谢您指出这是重复的。但是,接受的答案使用非标准类型的操作符。你能提出一个替代方案吗?根据MSalter的评论,静态char func(char [sizeof(&C :: helloworld)])应该工作吗? – NEWBIE 2010-12-04 14:19:20