gpt4 book ai didi

c++ - 错误 : cannot bind ‘std::basic_ostream’ lvalue to ‘std::basic_ostream&&’

转载 作者:IT老高 更新时间:2023-10-28 23:01:45 63 4
gpt4 key购买 nike

我已经看过几个关于这个的问题,特别是 Overloading operator<<: cannot bind lvalue to ‘std::basic_ostream<char>&&’很有帮助。它让我知道我的问题是我正在做一些 c++11 无法从中推断出类型的事情。

我认为我的问题的很大一部分是我正在使用的实例化类是模板化的,但最初是从指向非模板基类的指针中获得的。这是我从另一个关于如何将模板类对象放入 STL 容器的 stackoverflow.com 问题中建议的。

我的课:

class DbValueBase {
protected:
virtual void *null() { return NULL; } // Needed to make class polymorphic
};

template <typename T>
class DbValue : public DbValueBase {
public:
DbValue(const T&val) { data = new T(val); }
~DbValue() { if (data) delete data; }

T *data;

const T& dataref() const { return *data; }

friend std::ostream& operator<<(std::ostream& out, const DbValue<T>& val)
{
out << val.dataref();
return out;
}
}

还有,编译错误 database.cc:530:90: error: cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’ 的代码片段发生:

//nb:  typedef std::map<std::string,DbValueBase*>  DbValueMap;
const CommPoint::DbValueMap& db_values = cp.value_map();
for (auto i = db_values.cbegin() ; i != db_values.cend() ; i++) {
// TODO: Need to implement an ostream operator, and conversion
// operators, for DbValueBase and DbValue<>
// TODO: Figure out how to get a templated output operator to
// work...
// DbValue<std::string> *k = dynamic_cast<DbValue<std::string>*>(i->second);
std::cerr << " Database field " << i->first << " should have value " << *(i->second) << endl;
}

如果我的输出尝试打印 i->second ,它编译并运行,我看到了指针。如果我尝试输出 *(i->second) ,我得到编译错误。在 gdb 中单步执行时,似乎仍然知道 i->second是正确的类型

(gdb) p i->second
$2 = (DbValueBase *) 0x680900
(gdb) p *(i->second)
warning: RTTI symbol not found for class 'DbValue<std::string>'
$3 = warning: RTTI symbol not found for class 'DbValue<std::string>'
{_vptr.DbValueBase = 0x4377e0 <vtable for DbValue<std::string>+16>}
(gdb) quit

我希望我做错了什么。但是,它比我自己似乎能够弄清楚的要复杂得多。其他人看到我做错了什么或不完整的事情吗?

编辑:

@PiotrNycz 确实为我在下面提出的问题提供了一个很好的解决方案。然而,尽管目前在进行开发时打印值,但对这些 DbValue<> 的真正需求对象是让它们返回正确类型的值,然后我可以将其提供给数据库操作方法。我应该在我最初的问题中提到,打印是有值(value)的,但不是我目标的终点。

最佳答案

如果你想通过基指针打印对象 - 在基类中创建 ostream 运算符:

class DbValueBase {
protected:
virtual ~DbValueBase() {}
virtual void print(std::ostream&) const = 0;
friend std::ostream& operator << (std::ostream& os, const DbValueBase & obj)
{
obj.print(os); return os;
}
};

template <typename T>
class DbValue : public DbValueBase {
public:
void print(std::ostream& os) const
{
out << dataref();
}
};

关于c++ - 错误 : cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’ ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13347530/

63 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com