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

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

最佳答案

枚举类值被视为新类型,没有对其基础类型进行隐式转换。如果你想对它们使用 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 << "}";
  }

至于“为什么”会出现这样一个关于右值的奇怪错误——归咎于标准库实现者;)。

关于c++ - 无法理解模板和与构造函数相关的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30723036/

10-12 20:14
查看更多