Search code examples
c++templatesc++17

how to refer to typename's typename is template in C++?


I am working on a project which is nested templates. How to refer to typename's typename? See examples below.

template<typename T>
class point1{
   public:
     T x, y;
     point1(T v1, T v2):x(v1), y(v2){}
}
template<typename T>
class point2{
   public:
     T a, b;
     point2(T v1, T v2):a(v1), b(v2){}
}
template<typename pointarray>
class coordinates{
   public:
     pointarray & _pp;
   void printsum(){
   using pointtype = typename pointarry::value_type;
   // pointarray could be like vector<point1<int>>, deque<point2<double>>
   // now pointtype could be point1 or point2
   // there will be compiling issues in below.
   auto intORdouble = pointtype::value_type;
   intORdouble ssumm = 0;
  }
}

The more I learned about template in C++, the more complicated it seemed to be.


Solution

  • You have to define it.

    template<typename T>
    class point1{
       public:
         using value_type = T; 
    
         T x, y;
         point1(T v1, T v2):x(v1), y(v2){}
    };
    

    I assume pontarray is some default container, they have exactly that. If you must to reach in guts of some non-standard but not controlled by you template type, you may use template template parameters (that's an intentional repeat), or have to do that manually.

    To compare types, there is a type_traits tool:

    auto intORdouble = std::is_same<typename pointtype::value_type, int>::value;
    

    but do you actually need it to be a non-static run-time value? You can declare static constant in a number of ways.

    using isInteger = std::integral_constant< bool, 
                           std::is_same< typename pointtype::value_type,
                                         int >::value >;
    

    isInteger here would be a type whose whole purpose it to contain a static constexpr value of type bool returned by is_same.