C++,非模板类中的模板变量

标签 c++ templates

我正在使用以下模板类:

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; 
    .... 
};

如果我要创建一个对象线,需要写点的类型和线的类型

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

我觉得这毫无意义......如果点是双倍的,那么线也必须是双倍的......是否可以只模板化类 Line 中的指针而不模板化所有类,类似的东西

template <class T>
class Point2D;

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

和使用

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

最佳答案

不直接。你可以创建一个函数 make_line沿着 std::make_pair 的路线它根据输入类型隐式计算出返回类型,但它的返回类型仍然是 Line<double> .如果您正在构建匿名 Line,这将很有用。用于传递到另一个函数。

在 C++0X 中,auto 有了新的用途用于根据分配的表达式的类型声明隐式类型变量的关键字。

所以这将允许做这样的事情(无需更改您的 Point2DLine 类):

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));
     ...
}

关于C++,非模板类中的模板变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4501612/

相关文章:

c++ - 在此代码中验证半径时遇到问题

c++ - AWS CPP S3 SDK 是否支持 "Transfer acceleration"

c++ - 使用 QSignalMapper 将 QString 传递给父级的类方法

c++ - 在 MSVC 2017 中继承模板构造函数和错误 C2600

时间:2019-03-08 标签:c++Template[]overload

C++ 专门化单一成员函数

C++0x : conditional operator, x值和decltype

c++ - 如何转发元组类型以专门化其他模板?

c++ - 设备函数指针作为模板参数

c++ - 为什么 getchar_unlocked() 在 c/c++ 中更快?