无法理解模板和构造函数相关的错误

时间:2015-06-09 04:29:27

标签: c++ templates inheritance constructor

#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();

}

我正在尝试这段代码。 在编译时,我在这行中遇到错误:

cout << "Derived<T>{" << mValue << "; " << Base::mInitialize << "}";

,错误是

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)

我无法理解这个错误。有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

Base::mInitialize不会自动转换为

行中的int
cout << "Derived<T>{" << mValue << "; " << Base::mInitialize << "}";

使用:

cout << "Derived<T>{" << mValue << "; " << static_cast<int>(Base::mInitialize) << "}";

答案 1 :(得分:1)

您正在尝试致电operator<<以传输demo_initialize。您的代码中没有任何地方定义过此运算符,并且由于demo_initialize是您自己定义的枚举,因此标准库中没有operator<<

通过实施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); 
}

答案 2 :(得分:0)

将枚举类值视为新类型,而不对其基础类型进行隐式强制转换。如果您想对它们使用std::ostream& operator<<( std::ostream&, const demo_initialize& ),则需要提供一个,或使用:

void display() {
    auto mI = static_cast<std::underlying_type<demo_initialize>::type >(Base::mInitialize);
    std::cout << "Derived<T>{" << mValue << "; " << mI << "}";
  }

关于'为什么'这样一个关于rvalues的奇怪错误出现了 - 责怪标准库实现者;)。