Reputation: 57
I am using 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 an object Line, it is necessary to write type of the point and type of the Line
int main
{
Point2DC<double> p1(0,0);
Point2DC<double> p2(10,10);
Line<double> l(&p1,&p2);
...
}
I find it rather pointless... If points are double, so Line must be also double... Is it possible to templatize only pointers in class Line and do not templatize all class, something like that
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);
...
}
Upvotes: 4
Views: 1643
Reputation: 45533
Not directly. You can make a function make_line
along the lines of std::make_pair
that implicitly figures out the return type based on the input types, but its return type will still be Line<double>
. This is useful if you're constructing an anonymous Line
for passing into another function.
In C++0X, there's a new use of the auto
keyword for declaring an implicitly typed variable, based on the type of the assigned expression.
So this would allow to do something like this (without changing your 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));
...
}
Upvotes: 6