samedi 29 août 2020

Define two class enums in the same header file with the output operator overriden

I have the Colors.hpp header in which I would like to define the two enums that are seen in the code. Also, I would like to print the number value, so I have overridden the << operator for the two enums:

#ifndef COLORS_HPP
#define COLORS_HPP

#include <iostream>

namespace CliWidget {

enum class ForegroundColor {
    black   = 30, 
    red     = 31, 
    green   = 32, 
    yellow  = 33, 
    blue    = 34, 
    magenta = 35, 
    cyan    = 36, 
    white   = 37
};  

std::ostream& operator << (std::ostream& os, const ForegroundColor& fColor){
   os << fColor; 
   return os; 
}   

enum class BackgroundColor {
    black   = 40, 
    red     = 41, 
    green   = 42, 
    yellow  = 43, 
    blue    = 44, 
    magenta = 45, 
    cyan    = 46, 
    white   = 47
};  

std::ostream& operator << (std::ostream& os, const BackgroundColor& bColor){
   os << bColor; 
   return os; 
}   
}
#endif

The problem I'm having is that the compiler finds the two functions of operator override and seems that for it they are the same (multiple definitions) as the error shows.

In function CliWidget::operator<<(std::ostream&, CliWidget::ForegroundColor const&)': /home/albert/Projects/CliWidget/src/ColorsEnum.hpp:20: multiple definition of CliWidget::operator<<(std::ostream&, CliWidget::ForegroundColor const&)'

Should I only make one operator for the two enums, or there is a better solution?

Aucun commentaire:

Enregistrer un commentaire