Search code examples
c++c++11type-traits

Is there any type trait which controls member type(not member variable)


STL comes with many type traits like std::is_pointer, std::is_reference etc...

Lets say I have a class

class A 
{
   using type_member = void;     
}

Is there any type trait for controlling the type member and checking if it exists ?
Something like is_type_member_exist<typename A::type_member>();

I am both curious if a solution exist with C++17 and also curious about C++2003(at work I need this and I have vs2010 which has a bit C++11 support but not complete).


Solution

  • If type_member is public (and not private as in your question), I suppose you can do something like

    #include <iostream>
    
    template <typename X>
    struct with_type_member
     { 
       template <typename Y = X>
       static constexpr bool getValue (int, typename Y::type_member * = nullptr)
        { return true; }
    
       static constexpr bool getValue (long)
        { return false; }
    
       static constexpr bool value { getValue(0) };
     };
    
    class A 
     {
       public:
          using type_member = void;     
     };
    
    int main ()
     {
       std::cout << with_type_member<int>::value << std::endl; // print 0
       std::cout << with_type_member<A>::value << std::endl;   // print 1
     }
    

    Hope this helps.