0

Is there a way to access member-function from the friend class?

// foo.h

template<typename T>
class A
{
    bool operator()(Item* item)
    {
        ObjectClass c = get_class_from_item(item); // compiler error
        ...
    }
};

class B
{
    ...
    template<typename T> friend class A;
    ...
    ObjectClass get_class_from_item(Item* item);
};

If it matters I use gcc 4.5.2

jparthj
  • 1,606
  • 3
  • 20
  • 44
maverik
  • 5,508
  • 3
  • 35
  • 55

2 Answers2

3

If get_class_from_item is supposed to be some kind of Factory function, which it seems to be, you need to make it static. You get the error because your compiler is looking for a function named get_class_from_item in class A. It will never see the function in B because it is not in the scope and you don't have an instance of class B. Here is some more explanation on Wikipedia: http://en.wikipedia.org/wiki/Factory_function.

This should do it:

class A
{
    bool operator()(Item * item)
    {
        ObjectClass c = B::get_class_from_item(item);
        ...
    }
};

class B
{
    static ObjectClass get_class_from_item(Item* item);
};

Also, is there a reason that A needs to be a friend class of B? Or did you just do that trying to get get_class_from_itemto work? Does A need to be able to access some private elements of B? Think carefully about this, most of the time there are better ways of obtaining what you want instead of throwing away all encapsulation by using friend.

[Edit] Removed lines from code example to strip it to the bare minimum.

AVH
  • 11,349
  • 4
  • 34
  • 43
  • It's not a factory function. It just gets an `item` and returns `ObjectClass` that item holds like: `return classes[item->data(...)]`. OTOH I can't make `get_class_from_item` static, because it uses some members that cannot be static (they are changed in run-time). – maverik Apr 01 '11 at 08:41
  • The deal is that `A` doesn't have enough information to do its task. So I probably should fix the design. Thanks to all. – maverik Apr 01 '11 at 08:50
2

No, since get_class_from_item is a member function you need an instance of class B to call it.

Naveen
  • 74,600
  • 47
  • 176
  • 233