1

Is this answer considered "good" code or is it just an ugly hack?

And I would like to know how this is forward-declared (both classes).

When I just forward-declare the class with 2 template-parameters, it just always takes this one, no matter what value flag has.

I would like to do this because I have 2 special member functions which should behave differently on flag being true and I don't feel like reimplementing the whole class. Also, it should have the same name. According to this example, this seems to be possible.

And I have to forward-declare it because I'm creating a library in which we forward-declare everything.

Any idea?

Community
  • 1
  • 1
Atmocreations
  • 9,923
  • 15
  • 67
  • 102
  • @AraK: Do you want to defend your code? 8v) – Fred Larson Oct 26 '11 at 22:15
  • Thanks for the good responses. I still have one question left: `struct something : public something` looks means that a class is deriving itself which can't be. Therefore it's neither inheritance nor overriding. What else is it then? Is this "hiding" everyone talks about a standard? Or is it just luckily behaving that way? – Atmocreations Oct 28 '11 at 17:42

2 Answers2

2

It has the drawback that it doesn't really work. The base member function is not overridden, but it is just hidden by the derived class' function when you try to call it from outside. Which means if you call doSomething out of the base class (where presumably all your other functions live) it will call the base class doSomething which is not what is wanted.

The accepted answer on that question shows multiple ways for how you can solve your problem.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
1

In order to use specialisation its definition always has to be visible to the caller. If, for example, you have template <class Type, bool flag> struct something defined in one header and template <class Type> struct something<Type, true> : public something<Type, false> defined in the second one, to use the latter you have to include the second header. Without that you will always get the first, more generic type.

EDIT: the bit about forward-declaring got me thinking. If you want to use only type declaration, as in pointer variable, do the following:

Header

template <class Type, bool flag>
struct something;

struct Test
{
    something<int, true>* ptr; // definition not needed
    Test();
}

Source

#include "something.h" // header with template
#include "something_spec.h" // header with specialisation

Test::Test()
{
    ptr = new something<int, true>(); // specialisation used
}
gwiazdorrr
  • 6,181
  • 2
  • 27
  • 36