Stay Hungry , Stay Foolish

君子生非异也,善假于物也

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

#include <iostream>

struct Hello
{
    int helloworld() { return 0; }
};

struct Generic {};    

// SFINAE test
template <typename T>
class has_helloworld
{
    typedef char yes[1];
    typedef yes no[2];

    template <typename C> static yes& test( typeof(&C::helloworld) );
    template <typename C> static no& test(...);

public:
    enum { value = sizeof(test<T>(0)) == sizeof(yes) };
};

int main(int argc, char *argv[])
{
    std::cout << has_helloworld<Hello>::value << std::endl;
    std::cout << has_helloworld<Generic>::value << std::endl;
    return 0;
}

 

参考资料

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

SFINAE to check for inherited member functions

Substitution failure is not an error(SFINAE)

An introduction to C++'s SFINAE concept: compile-time introspection of a class member

深入浅出SFINAE

posted on 2016-08-16 11:22  octocat  阅读(428)  评论(0编辑  收藏  举报