1

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?

SOLVED:

There was two problems: declaring the static variable and the operator<< method. This fixed the issue.

operator std::string() const
   {
      return toString();
   }

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

and outside:

template<typename T>
constexpr RGB<T> RGB<T>::Red;

template<typename T>
constexpr RGB<T> RGB<T>::Green;

template<typename T>
constexpr RGB<T> RGB<T>::Blue;

template<class T>
std::ostream& operator<<(std::ostream & os, const RGB<T>& rgb)
{
    return os << rgb.toString();
}
Moia
  • 1,920
  • 1
  • 8
  • 27

0 Answers0