g++: declaration of a friend from within a namespace

Matthias Kaehlcke matthias@kaehlcke.net
Mon Jun 2 16:17:00 GMT 2008


Hi,

i'm trying to declare an operator in the default namespace to be a
friend of a class within another namespace:


namespace ns
{
  // forward declaration
  class MyClass;
}


// forward declaration
ns::MyClass operator+(ns::MyClass lhs, ns::MyClass rhs);


namespace ns
{
  class MyClass
  {
      friend MyClass ::operator+(MyClass, MyClass);

    private:
      int attribute;
  };
}


ns::MyClass operator+(ns::MyClass lhs, ns::MyClass rhs)
{
  ns::MyClass c;
  c.attribute = 7;
}


this fails with an compilation error:

foo.cpp:17: error: ISO C++ forbids declaration of ‘operator+’ with no
type


when removing the default namespace specifier ('::') from the friend
declaration the error message changes to:

foo.cpp: In function ‘ns::MyClass operator+(ns::MyClass,
ns::MyClass)’:
foo.cpp:21: error: ‘int ns::MyClass::attribute’ is private
foo.cpp:29: error: within this context

i.e. the friend declaration refers to an (unexisting) operator in the
namespace ns, where MyClass is defined.


after moving the operator from the default namespace to another one,
the compilation succeeds:

namespace ns
{
  // forward declaration
  class MyClass;
}


namespace other_ns
{
  // forward declaration
  ns::MyClass operator+(ns::MyClass lhs, ns::MyClass rhs);
}


namespace ns
{
  class MyClass
  {
      friend MyClass other_ns::operator+(MyClass, MyClass);

    private:
      int attribute;
  };
}


namespace other_ns
{
  ns::MyClass operator+(ns::MyClass lhs, ns::MyClass rhs)
  {
    ns::MyClass c;
    c.attribute = 7;
  }
}

i can't figure out what would be the correct friend declaration with
the operator in the default namespace. the build environment is gcc
v4.1.3 on a ubuntu gutsy gibbon box.

any pointer?
 
-- 
Matthias Kaehlcke
Embedded Linux Engineer
Barcelona

      The assumption that what currently exists must necessarily
        exist is the acid that corrodes all visionary thinking
                                                                 .''`.
    using free software / Debian GNU/Linux | http://debian.org  : :'  :
                                                                `. `'`
gpg --keyserver pgp.mit.edu --recv-keys 47D8E5D4                  `-



More information about the Gcc-help mailing list