C ++, template variable in class without template

I use the following template classes:

template <class T> class Point2D { private: T x; T y; ... }; template <class T> class Point2D; template <class T> class Line{ private: Point2D <T> *start; Point2D <T> *start; .... }; 

If I want to create a Line object, I need to write a point type and a Line type

 int main { Point2DC<double> p1(0,0); Point2DC<double> p2(10,10); Line<double> l(&p1,&p2); ... } 

I find it rather pointless ... If the points are double, then the line should also be double ... Is it possible to plan only patterns in the Line class and not templatize all classes, something like this

 template <class T> class Point2D; class Line{ private: template <class T> Point2D <T> *start; Point2D <T> *start; .... }; 

and use

 int main { Point2D<double> p1(0,0); Point2D<double> p2(10,10); Line l(&p1,&p2); ... } 
+4
source share
1 answer

Not directly. You can make a make_line function along std::make_pair lines that implicitly determines the return type based on input types, but its return type will be Line<double> . This is useful if you create an anonymous Line to pass to another function.

C ++ 0X uses a new use of the auto keyword to declare an implicitly typed variable depending on the type of expression assigned.

Thus, this will allow you to do something similar (without changing the Point2D or Line classes):

 template <class T> Line<T> make_line(Point2D<T> *p1, Point2D<T> *p2) { return Line<T> (p1, p2); } template <class T> void DoSomethingWithALine(const Line<T> &l) { .... } int main { Point2DC<double> p1(0,0); Point2DC<double> p2(10,10); // C++0X only: auto l = make_line(&p1,&p2); // Current C++: DoSomethingWithALine(make_line(&p1, &p2)); ... } 
+6
source

Source: https://habr.com/ru/post/1332922/


All Articles