mardi 17 avril 2018

Undefined reference to class when using std::cout [duplicate]

This question already has an answer here:

Consider this code:

rgb.h

namespace Company{
namespace Core{
constexpr int RGB_MIN = 0;
constexpr int RGB_MAX = 255;

template<typename T>
class RGB;

using RGBi = RGB<int>;

template<typename T>
class RGB
{
public:
   constexpr RGB() : R(0), G(0), B(0)
   {
   }

   constexpr RGB(T red, T green, T blue) : R(red), G(green), B(blue)
   {
   }

   static constexpr RGB<T> Red   = RGB<int>(RGB_MAX,RGB_MIN,RGB_MIN);
   static constexpr RGB<T> Green  = RGB<int>(RGB_MIN,RGB_MAX,RGB_MIN);
   static constexpr RGB<T> Blue = RGB<int>(RGB_MIN,RGB_MIN,RGB_MAX);

   operator std::string() const
   {
      std::ostringstream s;
      s << "RGB=" << R << "," << G << "," << B;
      return s.str();
   }
   T R, G, B;
};

template<class T>
std::ostream& operator<<(std::ostream & os, const RGB<T>& rgb)
{
    return os << rgb;
}

}
}

qt_addons.h

#include <QDebug>
QDebug operator <<(QDebug debug, const std::string& object)
{
   debug << QString::fromStdString(object);

   return debug;
}

main.cpp

#include <iostream>
#include "qt_addons.h"
#include "rgb.h"
int main()
{
   using namespace Company::Core;

   qDebug() << RGBi::Blue;

   return 0;
}

Everything works perfectly, but if I try to use a std::cout instead of a qDebug, it gives me an

'undefined reference to Company::Core::RGB::Blue'

If I try to initialize a normal variable it still works with qDdebug(), but it goes to segmentation fault with std::cout.

What am I missing?

Edit:

Adding or moving outside the declaration of RGB<T> Blue does not solve the problem giving "already defined" error and "static member must have an initializer" error, so it is not a duplicate of question as proposed.

As suggested in comments there's is an error too in the operator<< overload implementation which cause infinite recursion. It explains the segementation fault when trying to cout a normal RGBi variable, but not the main point.

Aucun commentaire:

Enregistrer un commentaire