0

I'm struggling with C++ templates. This is simplified version of my code. In real, I have it separated into .cpp and .h files, but I just made it short to show the problem.

#include <iostream>

template<typename T>
class GenericColor
{
};

template<typename T>
class RGB : public GenericColor<T>
{
public:
    HSV toHSV();
};

class HSV : public GenericColor<double>
{
};

The compilation result is:

prog.cpp:12:2: error: ‘HSV’ does not name a type
  HSV toHSV();
  ^

https://ideone.com/HnvC6F

stil
  • 5,306
  • 3
  • 38
  • 44
  • [When to use forward declaration?](http://stackoverflow.com/questions/553682/when-to-use-forward-declaration) – user703016 May 27 '14 at 13:18

3 Answers3

4

The compiler reads from top to bottom. You need to forward declare HSV.

put:

class HSV;

before class RGB

Salgar
  • 7,687
  • 1
  • 25
  • 39
  • 1
    Or move the definition of `HSV` before the definition of `RGB` since there are no dependencies anyway. – jasal May 27 '14 at 13:20
1

When the compiler reads the definition of RGB, HSV is not yet declared. You need to declare it before. The following code is correct:

template<typename T>
class GenericColor
{
};


class HSV : public GenericColor<double>
{
};

template<typename T>
class RGB : public GenericColor<T>
{
public:
    HSV toHSV();
};

there are cases where it is not easy to define classes in a suitable order. In that case, you can just declare the one you need, and define it later. That is named a forward-declaration. See the code below:

#include <iostream>

template<typename T>
class GenericColor
{
};

class HSV; // the forward-declaration

template<typename T>
class RGB : public GenericColor<T>
{
public:
    HSV toHSV();
};

// the definition of HSV
class HSV : public GenericColor<double>
{
};
lrineau
  • 6,036
  • 3
  • 34
  • 47
0

You need to define HSV before you can return it from a member function. In this instance, just cut paste the HSV class def above the RGB class def.

learnvst
  • 15,455
  • 16
  • 74
  • 121