对隐式和显式模板声明感到困惑

Cry*_*tal 0 c++ templates

我对隐式声明和显式声明感到困惑.我不知道为什么你需要明确说出或在某些时候.例如,

在我的main.cpp中

#include <iostream>
#include "Point.h"

int main()
{
    Point<int> i(5, 4);
    Point<double> *j = new Point<double> (5.2, 3.3);
    std::cout << i << *j;
    Point<int> k;
    std::cin >> k;
    std::cout << k;
}
Run Code Online (Sandbox Code Playgroud)

Point<int> k.为什么我必须使用显式声明?否则我会收到编译错误.或者我的Point.h文件中的编码不正确?

Point.h:

#ifndef POINT_H
#define POINT_H

#include <iostream>

template <class T>
class Point
{
public:
    Point();
    Point(T xCoordinate, T yCoordinate);

    template <class G>
    friend std::ostream &operator<<(std::ostream &out, const Point<G> &aPoint);

    template <class G>
    friend std::istream &operator>>(std::istream &in, const Point<G> &aPoint);

private:
    T xCoordinate;
    T yCoordinate;
};

template <class T>
Point<T>::Point() : xCoordinate(0), yCoordinate(0)
{}

template <class T>
Point<T>::Point(T xCoordinate, T yCoordinate) : xCoordinate(xCoordinate), yCoordinate(yCoordinate)
{}


template <class G>
std::ostream &operator<<(std::ostream &out, const Point<G> &aPoint)
{
    std::cout << "(" << aPoint.xCoordinate << ", " << aPoint.yCoordinate << ")";
    return out;
}

template <class G>
std::istream &operator>>(std::istream &in, const Point<G> &aPoint)
{
    int x, y;
    std::cout << "Enter x coordinate: ";
    in >> x;
    std::cout << "Enter y coordinate: ";
    in >> y;
    Point<G>(x, y);

    return in;
}

#endif
Run Code Online (Sandbox Code Playgroud)

ken*_*ytm 8

对于类模板,必须明确指定模板参数.

对于函数模板,可以隐式推断模板参数.

Point 是一个类,因此需要明确的声明.