【问题标题】:C++ template-id does not match any templateC++ 模板 ID 不匹配任何模板
【发布时间】:2021-07-23 17:25:32
【问题描述】:

嗨,我正在尝试重载

#include <iostream>
using namespace std;

template <class T, class U>
class Couple
{
public:
    T cle;
    U valeur;

public:
    Couple();
    Couple(T, U);
    friend ostream &operator<<<>(ostream &, Couple<T, U>);
};
template <class T, class U>
ostream &operator<<(ostream &os, Couple<T, U> Cpl)
{
    os << Cpl.cle << " : " << Cpl.valeur << endl;
    return os;
}

但它给了我这个错误我在互联网上尝试了所有东西

在 Couple.cpp:2 包含的文件中, 来自 main.cpp:2: Couple.h:在 'class Couple' 的实例化中: main.cpp:7:28:从这里需要 Couple.h:14:21:错误:模板 ID 'operator' for 'std::ostream& operator)' 确实不匹配任何模板声明

【问题讨论】:

  • 请告诉我们它失败的背景......

标签: c++ templates overloading friend


【解决方案1】:

需要提前声明算子模板。例如

// forward declaration for class template
template <class T, class U>
class Couple;
// declaration
template <class T, class U>
ostream &operator<<(ostream &os, Couple<T, U> Cpl);

template <class T, class U>
class Couple
{
    ...
    // friend declaration
    friend ostream &operator<<<>(ostream &, Couple<T, U>);
};

// definition
template <class T, class U>
ostream &operator<<(ostream &os, Couple<T, U> Cpl)
{
    ...
}

【讨论】:

  • 你能进一步解释一下吗?
  • @DhiaAmmar 您的friend 声明是指模板operator&lt;&lt; 的实例化,那么模板的声明必须在此之前存在,否则无法实例化(从模板声明)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 2011-08-07
  • 1970-01-01
相关资源
最近更新 更多