检查模板参数是否具有成员函数 [英] Checking whether a template argument has a member function
本文介绍了检查模板参数是否具有成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
可以写一个要检查函数是否存在的C ++模板?
这与我的早期问题.我想检查模板参数是否包含成员函数.
This is very similar to my earlier question. I want to check whether a template argument contains a member function or not.
我尝试了与上一个问题中接受的答案相似的代码.
I tried this code similar to that in the accepted answer in my previous 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概念的新手.
But I have no idea what should I put in place of ???
to make it work.
I am new to SFINAE concept.
推荐答案
Little modification of MSalters' idea from 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&)};
};
这篇关于检查模板参数是否具有成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文