#include <iostream>
#include <string>
using namespace std;
template <class S>
constexpr auto has_f_helper(int)
-> decltype(std::declval<S>().f(), std::true_type{});
template <class>
constexpr std::false_type has_f_helper(...);
template <class S>
using has_f = decltype(has_f_helper<S>(0));
template <class S>
void check_has_f()
{
if(has_f<S>()) //(has_f<S>()完成true_type的实例化,跟has_f<S>::value效果相同
{
cout<<"has f()"<<endl;
}
else
{
cout<<"no f()"<<endl;
}
}
class A
{
public:
void f();
};
class B{
};
int main()
{
check_has_f<A>();
check_has_f<B>();
return 0;
}
运行程序输出:
has f()
no f()