c++ - 与隐式和显式模板声明混淆

标签 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;
}

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

点.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

最佳答案

对于类模板,必须显式指定模板参数。

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

Point 是一个类,因此需要显式声明。

关于c++ - 与隐式和显式模板声明混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2970253/

相关文章:

c++ - 创建通用插入函数

c++ - 编译器何时可以推断模板参数?

java - TCP Java 客户端向 C++ 服务器发送数据

c++ - 将 16 位整数转换为 char 数组? (C++)

c++ - 模板模板参数的模板参数推导错误

c++ - 引用 "auto"函数作为模板参数

c++ - 'this' cannot be used in a constant expression error (C++) with this-> pointer variable

c++ - CERN 根目录 : Is is possible to plot pairs of x-y data points?

c++ - Visual Studio 2015:std::make_unique 中没有签名/未签名不匹配警告?

c++ - 模板 lambda 与带有模板 operator() 的仿函数