c++ - determine if struct has a member of specific type -


let's have struct foo , want determine if foo has int inside of it.

struct foo { int a; char c; }; has_int<foo>::value; // should true 

this basic form of i'd want, checking specific type:

has_type<foo, int>::value; 

if knew how above transform end goal is:

has_pointer<foo>::value; // false struct bar { int a; void *b; }; has_pointer<bar>::value; // true 

as i've tried, it's hard started, best can think of if pack of types contained in struct, write rest:

template <typename... ts> constexpr bool any_is_pointer() noexcept {     return (... || std::is_pointer_v<ts>); } 

what i'm asking seems may impossible. couldn't find duplicate, surprised couldn't might out there.

as others have said, want impossible right vanilla c++ arbitrary types. if able provide compile-time information alongside types need operate on in definition, can trying do.

you can boost fusion library's adapters, allow adapt existing structures become fusion containers or define new structures model fusion container. can use boost::mpl algorithms want types of compile-time checks want do.

consider example, using struct foo, , desired has_type compile time algorithm:

#include <boost/fusion/adapted/struct/define_struct.hpp> #include <boost/mpl/contains.hpp>  boost_fusion_define_struct(     (your_namespace), foo,      (int, a)      (char, c))  template<typename source_type, typename search_type> struct has_type {     typedef typename boost::mpl::contains<source_type, search_type>::type value_type;     static const bool value = value_type::value; };  #include <iostream>  int main() {     bool foo_has_int_pointer = has_type<your_namespace::foo, int*>::value;     bool foo_has_int = has_type<your_namespace::foo, int>::value;      std::cout << "foo_has_int_pointer: " << foo_has_int_pointer << "\n";     std::cout << "foo_has_int: " << foo_has_int << "\n";      your_namespace::foo my_foo;      my_foo.a = 10;     my_foo.c = 'x';      std::cout << "my_foo: " << my_foo.a << ", " << my_foo.c; } 

view output or mess example here: http://ideone.com/f0zc2m

as can see, use boost_fusion_define_struct macro define struct members you'd operate on @ compile-time. fusion provides several other macros defining structures this, macros adapting defined structures. check them out here.

of course, can tell down-side here. has_type work if source_type boost::mpl / boost::fusion sequence. you, means type want reason @ compile time in way, need define or adapt using macros. may not acceptable if you're writing library intended work arbitrary library-user-defined types.


Comments