c++ sfinae在模板元编程中的高级应用案例

   2024-10-01 4840
核心提示:判断类型是否有指定成员函数#include iostreamtemplate typename Tstruct has_member_function_foo{private:template typename U

判断类型是否有指定成员函数

#include <iostream>template <typename T>struct has_member_function_foo{private:    template <typename U>    static auto test(int) -> decltype(std::declval<U>().foo(), std::true_type{});        template <typename>    static std::false_type test(...);    public:    static constexpr bool value = std::is_same_v<decltype(test<T>(0)), std::true_type>;};struct A{    void foo() {}};struct B{    // No foo()};int main(){    std::cout << has_member_function_foo<A>::value << std::endl; // 1    std::cout << has_member_function_foo<B>::value << std::endl; // 0    return 0;}
判断类型是否为可调用对象
#include <iostream>template <typename T>struct is_callable{private:    // SFINAE test    template <typename U>    static auto test(int) -> decltype(std::declval<U>()(), std::true_type{});    template <typename>    static std::false_type test(...);public:    static constexpr bool value = std::is_same_v<decltype(test<T>(0)), std::true_type>;};struct F{    void operator()() {}};int main(){    std::cout << is_callable<F>::value << std::endl; // 1    std::cout << is_callable<int>::value << std::endl; // 0    return 0;}

这些案例展示了如何使用SFINAE技术来检查类型的特定特征,这是模板元编程中非常有用的一种技服。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号