Zac
Zac

Reputation: 3285

Private typedef used in public interface

Is there any reason to use private typedef's like the following? I see the benefits for having the typedef for reducing possible errors from the duplication, but those benefits can be achieved with a public typedef as well.

template < typename T >
class foo
{
  typedef typename T::some_type reused_type;
public:
  reused_type go();
};

Upvotes: 2

Views: 5486

Answers (2)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145389

One practical reason to use typedef is to avoid having to write typename everywhere, and one practical reason to have it be public is to avoid the situation where the same thing (in this case, the type) is referred to by a zillion different names.

Upvotes: 3

Kerrek SB
Kerrek SB

Reputation: 477388

One reason I can contrive is that things should be public if and only if they form part of the published interface. Bear in mind that templates can be specialized, and if the type in question is only relevant to some specializations but not others, it shouldn't be public. For example:

template <typename T> class Foo
{
    typedef typename T::value_type some_type;
    some_type x;
public:
    int act() { return x.get(); }
};

template <typename U> class Foo<std::vector<U*>>
{
    typedef typename U another_type;
    std::queue<another_type> q;
public:
    int act() { return q.size() / 3; }
};

In the example, you promise that Foo<T>::act() always returns an int, but nothing else.

Upvotes: 1

Related Questions