判断类中是否有指定名称的成员函数,或者变量,通过编译期进行计算:
C++17提供支持
// 判断某个对象是否具有某个函数 templatestruct Is_func : std::false_type {}; template struct Is_func ().OnInit())> > :std::true_type{}; class A { public: void OnInit(){} }; int main() { constexpr bool s = Is_func::value; // true constexpr bool j = Is_func ::value; // false }
使用void_t检查类型是否良构,在不求值语义中构造T并调用指定名称的函数。如果类型良构,那么调用特化版本的Is_func,否则调用主模板。
如果使用C++20,那么这将会更加的方便:
class A {
public:
void OnInit(){}
};
template
concept Ty = requires(T x) {
x.OnInit();
};
int main() {
constexpr bool s = Ty; // true
constexpr bool j = Ty; // false
}



