Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write std::is_member_{object,function}_pointer for static members?

The <type_traits> standard header defines metafunctions

template< class T >
struct is_member_object_pointer;

template< class T >
struct is_member_function_pointer;

template< class T >
struct is_member_pointer;

How, if possible, would one write a similar set of metafunctions for static member variables and functions? Why are these metafunctions not part of <type_traits> (or boost's equivalent)?

like image 278
seertaak Avatar asked Feb 10 '26 18:02

seertaak


1 Answers

They are part of <type_traits> under the name of std::void_t, since C++17. With that you check whether a specific class type has a member variable and/or functions.

For example to check if a class type Type has a member object x you would use something like:

template<class, class = std::void_t<>>
struct has_x : std::false_type {};

template<class T>
struct has_x<T, std::void_t<decltype( std::declval<T&>().x )>> : std::true_type {};

and similarly for a member function x() you would use:

template<class, class = std::void_t<>>
struct has_x_mem_fn : std::false_type {};

template<class T>
struct has_x_mem_fn<T, std::void_t<decltype( std::declval<T&>().x() )>> : std::true_type {};
like image 101
Shoe Avatar answered Feb 13 '26 10:02

Shoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!