I would like to do something like this:
template <typename T> class Foo { ... public: void DoSomething() { compile_time_if (T is ClassA) { m_T.DoThingOne(); m_T.DoThingTwo(); } DoSomeFooPrivateThing(); m_T.DoThingThree(); } T m_T; };
In this case, I know that all valid T implement DoThingThree , but only ClassA implements DoThingOne and DoThingTwo . This is not a duck, I only want to do this extra part for ClassA , and I don't want to add these methods to other possible T s. I cannot do casting because possible T are not inherited types.
I know that for this you can use an external helper template:
template <typename T> void Foo_DoSomething(T& t) { t.DoThingThree(); } template <> void Foo_DoSomething(ClassA& t) { t.DoThingOne(); t.DoThingTwo(); t.DoThingThree(); } template <typename T> class Foo { ... public: void DoSomething() { Foo_DoSomething(m_T); } ... };
However, now this external template does not have access to private members of Foo (cannot call DoSomeFooPrivateThing ), which limits its functionality, and publicly goes outside, which is not so. (Making an external method a friend just complicates the situation.)
Another seemingly reasonable option is its internal implementation:
template <typename T> class Foo { ... public: void DoSomething() { DoSomethingImpl(m_T); } ... private: template <typename T2> void DoSomethingImpl(T2& t) { DoSomeFooPrivateThing(); t.DoThingThree(); } template <> void DoSomethingImpl(ClassA& t) { t.DoThingOne(); t.DoThingTwo(); DoSomeFooPrivateThing(); t.DoThingThree(); } ... };
But this requires duplication of the external type of the template and parameter. This is probably acceptable, but still seems a bit odd. Unfortunately, it doesnโt actually compile (at least not in GCC, since it jeopardizes specialization within classes).
Is there a better way to do this?
c ++ c ++ 11 templates c ++ 03
Miral
source share