如何检查这些结构是否具有称为 "Foo" 的特定类型?
How can I check if these structs has the specific type called "Foo"?
#include <iostream>
/**** 在这里应用sfinae方法我很困惑******/
template <typename T>
struct hasTypeFoo {
//..
static constexpr bool value = true;
};
////////////////////////////////////////// ////
struct A {
using Foo = int;
};
struct B {
};
int main()
{
constexpr bool b1 = hasTypeFoo<A>::value;
constexpr bool b2 = hasTypeFoo<B>::value;
std::cout << b1 << b2;
}
使用std::void_t
:
template<typename T, typename = void>
struct hasTypeFoo : std::false_type { };
template<typename T>
struct hasTypeFoo<T, std::void_t<typename T::Foo>> : std::true_type { };
关于 std::void_t
如何工作的很好的解释,可以在 this question 中找到。如果 typename T::Foo
格式不正确,它在这里用于静默拒绝特化。
您可以使用 partial specialization 来完成。例如
// primary template
template <typename T, typename = void>
struct hasTypeFoo {
static constexpr bool value = false;
};
// partial specialization for types containing type Foo
template <typename T>
struct hasTypeFoo<T, std::void_t<typename T::Foo>> {
static constexpr bool value = true;
};
#include <iostream>
/**** 在这里应用sfinae方法我很困惑******/
template <typename T>
struct hasTypeFoo {
//..
static constexpr bool value = true;
};
////////////////////////////////////////// ////
struct A {
using Foo = int;
};
struct B {
};
int main()
{
constexpr bool b1 = hasTypeFoo<A>::value;
constexpr bool b2 = hasTypeFoo<B>::value;
std::cout << b1 << b2;
}
使用std::void_t
:
template<typename T, typename = void>
struct hasTypeFoo : std::false_type { };
template<typename T>
struct hasTypeFoo<T, std::void_t<typename T::Foo>> : std::true_type { };
关于 std::void_t
如何工作的很好的解释,可以在 this question 中找到。如果 typename T::Foo
格式不正确,它在这里用于静默拒绝特化。
您可以使用 partial specialization 来完成。例如
// primary template
template <typename T, typename = void>
struct hasTypeFoo {
static constexpr bool value = false;
};
// partial specialization for types containing type Foo
template <typename T>
struct hasTypeFoo<T, std::void_t<typename T::Foo>> {
static constexpr bool value = true;
};