c++ - friend method from a different namespace -
i have following situation. have class foo
inside own namespace my_lib
:
namespace my_lib{ template<typename t> class foo{ t data; public: // blah blah }; }
i trying interface library has own namespace other_lib
. putting interface inside wrapper
namespace in own my_lib
. copy method my_lib::wrapper::copy
need access my_lib::foo::data
need implement following:
namespace my_lib{ namespace wrapper{ template<typename t> void copy(const foo<t>& my_foo, other_lib::foo<t>& other_foo) { // copy my_foo.data other_foo } } }
to accomplish my_lib::wrapper::copy
method needs friend of my_lib::foo
class. can accomplish series of forward declarations in foo.h
// forward declare other_lib::foo namespace other_lib{ template<typename t> class foo; } namespace my_lib{ // forward declare wrapper::copy namespace wrapper{ template<typename t> void copy(const foo<t>& my_foo, other_lib::foo<t>& other_foo); } template<typename t> class foo{ t data; friend void copy(const foo<t>& my_foo, other_lib::foo<t>& other_foo); public: // blah blah }; }
this works don't it. 1 thing adds lot of stuff file otherwise unrelated other_lib
, wrapper
namespaces. also, use of other library optional in code, if includes foo.h
going see sort of unrelated forward declarations , start wonder why ...
how can fix design?
syntactic tricks friend
work on other namespaces aside, proper way fix design. interface of foo simply not complete if needs grant copy()
function in unrelated namespace friend access.
one way go put copy()
inside foo
(and other algorithm users of foo need). when done right, leads complete , usable class foo
. e.g. take @ std::list
has it's own sort()
member function take advantage of list implementation details. however, can lead bloated class interface foo
(just @ std::string
), it's not recommended general rule.
alternatively, provide minimal set of data access member functions (preferably iterators, not handles raw data) other classes can implement algorithms work on foo
. regular container (array, vector etc.) data representation inside foo
, recommendation general use.
however, since class foo
has tricky sparse matrix representation, should try algorithms-as-members-approach first.
Comments
Post a Comment