I have written a small class Dice that imitates the behavior of real dice and templated class Singleton that Dice can inherit from. I have written operator<< for class Dice but somehow compiler is having problems with finding it. I have overloaded << operators for Dice , Sinlgeton<Dice> and std::vector<int> which is returned from some Dice methods and it’s handy to have it.
I use Qt creator 2.5 with gcc 4.7 on ubuntu.
/home/USER/programming/cpp_yahtzee/main.cpp:12: error: no match for
‘operator<<’ in ‘std::operator<< >((* &
std::cout), ((const char*)”hello”)) << (&
Singleton::Instance())->Dice::getLastThrow()’
and this is the codes that produces this error :
std::cout << "hello" << Dice::Instance().getLastThrow();
EDIT
Yet this outputs what expected with no error at all :
std::cout << Dice::Instance()
Maybe that’s a problem with my compiler gcc/g++ 4.7 (tried gcc/g++ 4.6.3 and the effect is the same) ?
My sinlgeton class
template <typename T>
class Singleton
{
public:
static T& Instance();
Singleton() {}
private:
//declare them to prevent copies
Singleton(Singleton const&);
void operator=(Singleton const&);
};
template<typename T>
T& Singleton<T>::Instance()
{
static T _instance;
return _instance;
}
Dice class :
class Dice : public Singleton<Dice>
{
private:
std::vector<int> _lastThrow;
public:
Dice();
std::vector<int> generateThrow();
friend std::ostream& operator<<(std::ostream& os, const Dice& dice);
friend std::ostream& operator<<(std::ostream& os, const Singleton<Dice>& dice);
friend std::ostream& operator<<(std::ostream& os, const std::vector<int>& vect);
//accessor method - returning last throw
const std::vector<int>& getLastThrow();
//rethrowing {1,4} - dice #1 and #4
std::vector<int> Rethrow(const std::vector<int>& objects);
};
std::ostream& operator<<(std::ostream& os, const Dice& dice)
{
for (std::vector<int>::const_iterator it = dice._lastThrow.begin(); it != dice._lastThrow.end(); ++it) {
os << *it;
}
return os;
}
std::ostream& operator<<(std::ostream& os, const Singleton<Dice>& dice)
{
for (std::vector<int>::const_iterator it = dice.Instance().getLastThrow().begin(); it != dice.Instance().getLastThrow().end(); ++it) {
os << *it;
}
return os;
}
std::ostream& operator<<(std::ostream& os, const std::vector<int>& vect)
{
for (std::vector<int>::const_iterator it = vect.begin(); it != vect.end(); ++it) {
os << *it;
}
return os;
}
std::vector<int> Dice::generateThrow()
{
static std::vector<int> v(5);
for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
(*it) = rand()%(DICE_MAX)+1;
}
_lastThrow = v;
return v;
}
Now I cannot do something like this :
std::cout << Dice::Instance().generateThrow();
EDIT
Ilya Lavrenov’s method is working although this is not what I want because this requires creating a local variable. I have a problem somewhere with the Singleton class.
Some changes of your code and now its compiles well. And operator << also works well