阅读量:120
- 判断类型是否有指定成员函数
#include
template <typename T>
struct has_member_function_foo
{
private:
template <typename U>
static auto test(int) -> decltype(std::declval().foo(), std::true_type{});
template <typename>
static std::false_type test(...);
public:
static constexpr bool value = std::is_same_v<decltype(test(0)), std::true_type>;
};
struct A
{
void foo() {}
};
struct B
{
// No foo()
};
int main()
{
std::cout << has>::value << std class="hljs-comment">// 1
std::cout << has>::value << std class="hljs-comment">// 0
return 0;
}
- 判断类型是否为可调用对象
#include
template <typename T>
struct is_callable
{
private:
// SFINAE test
template <typename U>
static auto test(int) -> decltype(std::declval()(), std::true_type{});
template <typename>
static std::false_type test(...);
public:
static constexpr bool value = std::is_same_v<decltype(test(0)), std::true_type>;
};
struct F
{
void operator()() {}
};
int main()
{
std::cout << is>::value << std class="hljs-comment">// 1
std::cout << is class="hljs-type">int>::value << std class="hljs-comment">// 0
return 0;
}
这些案例展示了如何使用SFINAE技术来检查类型的特定特征,这是模板元编程中非常有用的一种技服。