vendredi 9 avril 2021

operator<< overload resolution (C++)

The code below gives an error in the a::b::print function: Invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'Foo').

The error goes away if I comment out the operator<< overload in namespace b. But I don't understand why that makes a difference because it has a different signature to the operator<< overload in namspace a. What's going on?!

#include <iostream>

class Foo {};

namespace a {

  std::ostream &operator<<(std::ostream &os, Foo &foo);
  void print(Foo& foo) {
    std::cout << foo;
  }

  namespace b {
    std::ostream &operator<<(std::ostream &os, double d); // uncomment to resolve error
    void print(Foo& foo) {
      std::cout << foo; // error here
    }
  }
}

Aucun commentaire:

Enregistrer un commentaire