查找类型是否具有特定成员的更通用方法?
More general way to find if a type has a certain member?
我正在尝试做一些事情来告诉我一个类型在编译时是否有某个函数/变量。我知道已经发布了解决方案,但这些都需要对每个不同的检查进行复制粘贴或宏。我想知道是否有更通用的方法来做到这一点。
也许语法如下:
bool has_certain_member = has<type, member>::value;
相对于:
DEFINE_MEMBER_CHECK(member)
bool has_certain_member = CHECK_FOR_MEMBER(type);
其中 DEFINE_MEMBER_CHECK 定义了一个助手类型来检查该特定成员,CHECK_FOR_MEMBER 获取特定类型的值。
有没有办法将指向成员的指针作为模板参数传递?或者您可能会将其作为参数传递给 constexpr 函数?
这就是 is_detected
的目的
#include<experimental/type_traits>
template<typename T>
using foo_t = decltype(std::declval<T>().foo());
template<typename T>
constexpr bool has_foo = std::experimental::is_detected_v<foo_t, T>;
并将其用作
struct Fooer { void foo() {} };
struct Barer { void bar() {} };
void test()
{
static_assert(has_foo<Fooer>);
static_assert(!has_foo<Barer>);
}
我正在尝试做一些事情来告诉我一个类型在编译时是否有某个函数/变量。我知道已经发布了解决方案,但这些都需要对每个不同的检查进行复制粘贴或宏。我想知道是否有更通用的方法来做到这一点。
也许语法如下:
bool has_certain_member = has<type, member>::value;
相对于:
DEFINE_MEMBER_CHECK(member)
bool has_certain_member = CHECK_FOR_MEMBER(type);
其中 DEFINE_MEMBER_CHECK 定义了一个助手类型来检查该特定成员,CHECK_FOR_MEMBER 获取特定类型的值。
有没有办法将指向成员的指针作为模板参数传递?或者您可能会将其作为参数传递给 constexpr 函数?
这就是 is_detected
的目的
#include<experimental/type_traits>
template<typename T>
using foo_t = decltype(std::declval<T>().foo());
template<typename T>
constexpr bool has_foo = std::experimental::is_detected_v<foo_t, T>;
并将其用作
struct Fooer { void foo() {} };
struct Barer { void bar() {} };
void test()
{
static_assert(has_foo<Fooer>);
static_assert(!has_foo<Barer>);
}