温馨提示×

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

c++
小樊
84
2024-08-15 16:07:41
栏目: 编程语言

  1. 判断类型是否有指定成员函数
#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;
}
  1. 判断类型是否为可调用对象
#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技术来检查类型的特定特征,这是模板元编程中非常有用的一种技服。

0