如何调用操作员模板?

Ede*_*dee 4 c++ templates class operator-overloading c++11

我对如何实例化此模板感到有些困惑。我知道,简单地使用friend会员身份会实现我想要的东西会更容易,但是如果我强迫这样做,该怎么办?我只是想弄清楚。(顺便说一句,我知道这个模板似乎毫无意义),我只想使其编译即可。

#include <iostream>

template <typename T>
inline std::ostream& operator<< (std::ostream& os, const T& date)
{
    os << date.getD() << " " << date.getM() << " " << date.getY() << "\n";
    return os;
}

class Date 
{
private:
    int dd, mm, yy;
public:
    Date(int d, int m, int y) : dd(d), mm(m), yy(y) {}
    int getD() const;
    int getM() const;
    int getY() const;
};

int Date::getD() const {  return dd; }

int Date::getM() const {  return mm; }

int Date::getY() const {  return yy; }

int main(int argc, char const *argv[])
{
    Date dat(1, 2, 2003);
    std::cout << <Date> dat;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 6

两个问题:

  1. 您正在声明operator<<可以接受任何类型的模板;这将导致与的歧义问题std::operator<<

  2. 以运算样式调用运算时,不能显式指定模板参数。(您可以使用类似丑陋的函数样式来执行此操作operator<< <Date>(std::cout, dat);)实际上,您不需要指定它,可以在此处推断出template参数。

您可以将代码更改为

std::ostream& operator<< (std::ostream& os, const Date& date) {
    os << date.getD() << " " << date.getM() << " " << date.getY() <<"\n";
    return os;
}
Run Code Online (Sandbox Code Playgroud)

然后

Date dat(1,2,2003);
std::cout << dat;
Run Code Online (Sandbox Code Playgroud)

生活