Checking whether class T has a Member member with void_t

So here is the code:

template<typename, typename, typename = void>
struct has_member_type : false_type {};

template<typename T, typename Member>
struct has_member_type<T, Member, void_t<typename T::Member>> : true_type {};

struct foo { using bar = int; };

int main()
{
    std::cout << has_member_type<foo, typename foo::bar>::value;
}

I am trying to check if a foomember has a type bar. It works fine if the implementation does not specify the name of the type member, but in this way the name is hardcoded into the implementation, which does not work for me.

The question that is being repeated is not close to my question. As I explained in the previous paragraph, it is good when the type is hardcoded into the implementation, but I cannot get it to work when I specify the type from the outside (this is a specific problem). The code compiles fine, but leads to incorrect results.

+4
source share
2 answers

, typename foo::bar int, , SFINAE.

, , T::bar, . , std::experimental::is_detected. , , *:

template<typename, template <typename> class, typename = void>
struct is_detected : false_type {};

template<typename T, template <typename> class Op>
struct is_detected<T, Op, void_t<Op<T>>> : true_type {};

, :

template <typename T> using bar_t = typename T::bar;

:

is_detected <foo, bar_t>::value

*: , , . , variadic . std::experimental::is_detected, .

+6

N4487 :

template <typename T, typename F>
constexpr auto test(F f) -> decltype(f(std::declval<T&>()), true) {return true;}

template <typename, typename... F>
constexpr bool test(F...) {return false;}

#define HAS_DATA(Name, ...) (test<__VA_ARGS__>([] (auto& t) -> decltype(&std::decay_t<decltype(t)>::Name) {}))
#define HAS_TYPE(Name, ...) (test<__VA_ARGS__>([] (auto& t) -> typename std::decay_t<decltype(t)>::Name {}))

cout.

+2

Source: https://habr.com/ru/post/1625146/


All Articles