尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

模板严格判断类里是否有某函数(类名+函数名+形参+返回类型)

模板严格判断类里是否有某函数(类名+函数名+形参+返回类型) 你的 has_foo trait 写对了吗签名严格匹配和能调用是两回事template typename T, typename void struct has_exact_foo : std::false_type {}; template typename T struct has_exact_fooT, std::void_tdecltype(static_castvoid(T::*)(int)(T::foo)) : std::true_type {}; struct A1 { void foo(int) {} }; struct B1 { int foo(int) { return 0; } }; struct C1 { void foo(long) {} }; struct D1 {}; struct E1 { void foo(int) const {} }; struct F1 { void foo(int) {} void foo(double) {} }; int main() { if(has_exact_fooA1::value) // true精确匹配 std::cout has_exact_fooA::value 为true std::endl; if(!has_exact_fooB1::value) // false返回值不匹配 std::cout !has_exact_fooB::value 为true std::endl; if (!has_exact_fooC1::value) // false参数类型不匹配 std::cout !has_exact_fooC::value 为true std::endl; if (!has_exact_fooD1::value) // false没有 foo std::cout !has_exact_fooD::value 为true std::endl; if (!has_exact_fooE1::value) // falseconst 版本不匹配 std::cout !has_exact_fooE::value 为true std::endl; if(has_exact_fooF1::value)//通过 std::cout has_exact_fooF::value 为true std::endl; return 1; } 输出 has_exact_fooA::value 为true !has_exact_fooB::value 为true !has_exact_fooC::value 为true !has_exact_fooD::value 为true !has_exact_fooE::value 为true has_exact_fooF::value 为true
返回列表