Checking whether a template argument has a member function [duplicate]

十年热恋 提交于 2019-12-30 10:36:36

问题


Possible Duplicate:
Is it possible to write a C++ template to check for a function's existence?

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
}

But I have no idea what should I put in place of ??? to make it work. I am new to SFINAE concept.


回答1:


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&)};
};


来源:https://stackoverflow.com/questions/4353878/checking-whether-a-template-argument-has-a-member-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!