sfinae - C++: providing a class function in templated class on existence of named member in its templated type? -


i trying following: templated class should provide functions dependend on whether or not type has been templated contains member variable given name. example following pseudocode should provide "printid()" when templated struct/class has member called "id":

#include <iostream> #include <type_traits>  struct { int id; }; struct b { };  template<typename t> class foo {   t myvar;  public:   #if exists t.id   (or alternative: #if exists myvar.id)   printid() { std::cout << "i have element id."; }   #endif };  int main(){   foo<a> ok;   ok.printid();   // should compile , execute    foo<b> nok;   nok.printid();  // should not compile   return 0; } 

digging around sfinae, traits, std::enable_if , stackoverflow, think can done ... somehow. somehow fail combine enable_if the following snippet question how detect whether there specific member variable in class?:

template<typename t, typename = void> struct has_id : std::false_type { };  template<typename t> struct has_id<t, decltype(std::declval<t>().id, void())> : std::true_type { }; 

any appreciated.

yep, it's possible. here's example:

template<typename t> class foo {   t myvar;  public:   template <class _t = t,             class = typename std::enable_if<                       !std::is_function<decltype(_t::id)>::value>                     ::type>   void printid() { std::cout << "i have element id."; } }; 

specifically, note how we're "taking in" t _t in order not force constraint on class template parameter (which make class un-compileable). instead, we're creating new, independent template member function, doesn't force on t itself—it "happens to" use default argument. that's key part.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -