перегрузка оператора друга << для шаблона класса - PullRequest
51 голосов
/ 11 января 2011

Я прочитал пару вопросов, касающихся моей проблемы, на StackOverflow.com, и ни один из них, похоже, не решил мою проблему.Или я, возможно, сделал это неправильно ... Перегруженный << работает, если я превращаю это в встроенную функцию.Но как мне заставить это работать в моем случае?

warning: friend declaration std::ostream& operator<<(std::ostream&, const D<classT>&)' declares a non-template function

warning: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) -Wno-non-template-friend disables this warning

/tmp/cc6VTWdv.o:uppgift4.cc:(.text+0x180): undefined reference to operator<<(std::basic_ostream<char, std::char_traits<char> >&, D<int> const&)' collect2: ld returned 1 exit status

Код:

template <class T>
T my_max(T a, T b)
{
   if(a > b)      
      return a;
   else
      return b;
}

template <class classT>
class D
{
public:
   D(classT in)
      : d(in) {};
   bool operator>(const D& rhs) const;
   classT operator=(const D<classT>& rhs);

   friend ostream& operator<< (ostream & os, const D<classT>& rhs);
private:
   classT d;
};


int main()
{

   int i1 = 1;
   int i2 = 2;
   D<int> d1(i1);
   D<int> d2(i2);

   cout << my_max(d1,d2) << endl;
   return 0;
}

template <class classT>
ostream& operator<<(ostream &os, const D<classT>& rhs)
{
   os << rhs.d;
   return os;
}

Ответы [ 5 ]

137 голосов
/ 11 января 2011

Это один из тех часто задаваемых вопросов, у которых разные подходы, которые похожи, но на самом деле не одинаковы.Три подхода различаются в том, кого вы объявляете другом вашей функции, а затем в том, как вы ее реализуете.

Экстраверт

Объявите все экземплярышаблон как друзья.Это то, что вы приняли в качестве ответа, а также то, что предлагает большинство других ответов.При таком подходе вы без необходимости открываете свою конкретную инстанцию ​​D<T>, объявляя друзьям все operator<< инстанцирования.Таким образом, std::ostream& operator<<( std::ostream &, const D<int>& ) имеет доступ ко всем внутренним элементам D<double>.

template <typename T>
class Test {
   template <typename U>      // all instantiations of this template are my friends
   friend std::ostream& operator<<( std::ostream&, const Test<U>& );
};
template <typename T>
std::ostream& operator<<( std::ostream& o, const Test<T>& ) {
   // Can access all Test<int>, Test<double>... regardless of what T is
}

Интроверты

Объявляют только конкретную реализацию оператора вставки какдруг.D<int> может понравиться оператор вставки, когда он применяется к самому себе, но он не хочет иметь ничего общего с std::ostream& operator<<( std::ostream&, const D<double>& ).

Это может быть сделано двумя способами, простым способом, как предложил @Emery Berger,который является оператором, что также является хорошей идеей по другим причинам:

template <typename T>
class Test {
   friend std::ostream& operator<<( std::ostream& o, const Test& t ) {
      // can access the enclosing Test. If T is int, it cannot access Test<double>
   }
};

В этой первой версии вы не создаете шаблон operator<<, а скореене шаблонная функция для каждого экземпляра шаблона Test.Опять же, разница невелика, но это в основном эквивалентно добавлению вручную: std::ostream& operator<<( std::ostream&, const Test<int>& ) при создании экземпляра Test<int> и другой аналогичной перегрузке при создании экземпляра Test с помощью double или с любым другим типом.

Третий вариант более громоздкий.Не вставляя код и используя шаблон, вы можете объявить один экземпляр вашего шаблона другом вашего класса, не открывая себя для всех других экземпляров:

// Forward declare both templates:
template <typename T> class Test;
template <typename T> std::ostream& operator<<( std::ostream&, const Test<T>& );

// Declare the actual templates:
template <typename T>
class Test {
   friend std::ostream& operator<< <T>( std::ostream&, const Test<T>& );
};
// Implement the operator
template <typename T>
std::ostream& operator<<( std::ostream& o, const Test<T>& t ) {
   // Can only access Test<T> for the same T as is instantiating, that is:
   // if T is int, this template cannot access Test<double>, Test<char> ...
}

Использование экстраверта

Тонкое различие между этим третьим вариантом и первым заключается в том, насколько вы открыты для других классов.Примером злоупотребления в версии extrovert может быть тот, кто хочет получить доступ к вашим внутренним ресурсам и делает это:

namespace hacker {
   struct unique {}; // Create a new unique type to avoid breaking ODR
   template <> 
   std::ostream& operator<< <unique>( std::ostream&, const Test<unique>& )
   {
      // if Test<T> is an extrovert, I can access and modify *any* Test<T>!!!
      // if Test<T> is an introvert, then I can only mess up with Test<unique> 
      // which is just not so much fun...
   }
}
15 голосов
/ 11 января 2011

Вы не можете объявить друга таким образом, вам нужно указать для него другой тип шаблона.

template <typename SclassT>
friend ostream& operator<< (ostream & os, const D<SclassT>& rhs);

note SclassT, чтобы он не затенял classT.При определении

template <typename SclassT>
ostream& operator<< (ostream & os, const D<SclassT>& rhs)
{
  // body..
}
3 голосов
/ 11 января 2011

Это сработало для меня без каких-либо предупреждений компилятора.

#include <iostream>
using namespace std;

template <class T>
T my_max(T a, T b)
{
  if(a > b)
    return a;
  else
    return b;
}

template <class classT>
class D
{
public:
  D(classT in)
    : d(in) {};

  bool operator>(const D& rhs) const {
    return (d > rhs.d);
  }

  classT operator=(const D<classT>& rhs);

  friend ostream& operator<< (ostream & os, const D& rhs) {
    os << rhs.d;
    return os;
  }

private:
  classT d;
};


int main()
{

  int i1 = 1;
  int i2 = 2;
  D<int> d1(i1);
  D<int> d2(i2);

  cout << my_max(d1,d2) << endl;
  return 0;
}
0 голосов
/ 11 января 2011

Я думаю, вам не стоит заводить друзей.

Вы можете создать открытый вызов метода print, что-то вроде этого (для не шаблонного класса):

std::ostream& MyClass::print(std::ostream& os) const
{
  os << "Private One" << privateOne_ << endl;
  os << "Private Two" << privateTwo_ << endl;
  os.flush();
  return os;
}

и затем вне класса (но в том же пространстве имен)

std::ostream& operator<<(std::ostream& os, const MyClass& myClass)
{
  return myClass.print(os);
}

Я думаю, что это должно работать и для шаблонного класса, но я еще не тестировал.

0 голосов
/ 11 января 2011

Вот, пожалуйста:

#include <cstdlib>
#include <iostream>
using namespace std;

template <class T>
T my_max(T a, T b)
{
   if(a > b)      
      return a;
   else
      return b;
}

template <class classT>
class D
{
public:
   D(classT in)
      : d(in) {};
   bool operator>(const D& rhs) const { return d > rhs.d;};
   classT operator=(const D<classT>& rhs);

   template<class classT> friend ostream& operator<< (ostream & os, const D<classT>& rhs);
private:
   classT d;
};

template<class classT> ostream& operator<<(ostream& os, class D<typename classT> const& rhs)
{
    os << rhs.d;
    return os;
}


int main()
{

   int i1 = 1;
   int i2 = 2;
   D<int> d1(i1);
   D<int> d2(i2);

   cout << my_max(d1,d2) << endl;
   return 0;
}
...