#include <iostream>
#include <vector>
#include <string>
using namespace std;
enum class demo_initialize { a = 1, b, c, d };
class Base {
public:
Base(demo_initialize initialize) : mInitialize(initialize) {}
protected:
demo_initialize mInitialize;
};
template <typename T>
class Derived : public Base
{
public:
Derived(T &value, demo_initialize initialize = demo_initialize::a) : Base(initialize), mValue(value), mLen(sizeof(T))
{
}
void display() {
cout << "Derived<T>{" << mValue << "; " << Base::mInitialize << "}";
}
protected:
T &mValue;
size_t mLen;
};
int main()
{
string string_to_reference = "world";
Derived<string> obj(string_to_reference, demo_initialize::c);
obj.display();
}
I was trying this piece of code. while compiling I got error in this line:
cout << "Derived<T>{" << mValue << "; " << Base::mInitialize << "}";
and the error was
In instantiation of 'void Derived<T>::display() [with T = std::basic_string<char>]':
37:17: required from here
26:49: error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'
In file included from /usr/include/c++/4.9/iostream:39:0,
from 1:
/usr/include/c++/4.9/ostream:602:5: note: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = demo_initialize]'
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
I am not able to understand this error. Can somebody help me in solving this?
Base::mInitialize is not automatically cast to an int in the line
cout << "Derived<T>{" << mValue << "; " << Base::mInitialize << "}";
Use:
cout << "Derived<T>{" << mValue << "; " << static_cast<int>(Base::mInitialize) << "}";
You are attempting to call operator<< to stream a demo_initialize. Nowhere in your code have you defined this operator, and since demo_initialize is an enum that you defined yourself, there is no operator<< for it in the standard library either.
Solve this by implementing operator<<(std::ostream &os, demo_initialize out):
std::ostream& operator<<(std::ostream &os, demo_initialize out) {
//Or some other logic, depending on the output format that you want.
return os << static_cast<std::underlying_type_t<demo_initialize>>(out);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With