[英]Standard container for incomplete types
i'm having a little problem with containers and incomplete types. 我在容器和不完整类型方面有一些问题。
I have this code: 我有以下代码:
template<typename T>
class IncompleteType
{ /*Class Definition*/ }
On another class i want to use a vector of incomplete types. 在另一个类上,我想使用不完整类型的向量。 This class serializes c-style structs to strings, so the behaviour is the same, no matter what type i'm supplying.
此类将c样式结构序列化为字符串,因此无论我提供哪种类型,其行为都相同。
However, when i do this: 但是,当我这样做时:
std::vector<IncompleteType>
or this: 或这个:
std::vector<IncompleteType*>
The compiler complains that i'm not supplying argument list for template class. 编译器抱怨我没有为模板类提供参数列表。
What i want to do is something like this: 我想做的是这样的:
IncompleteType<Type1> a;
IncompleteType<Type2> b;
std::vector<IncompleteType*> vector;
vector.push_back(&a);
vector.push_back(&b);
Is there a way to have a container to incomplete types? 有没有办法让容器容纳不完整的类型?
Is this the wrong way to achieve polymorphism? 这是实现多态的错误方法吗?
Thanks! 谢谢!
You do not have an incomplete type - you've got a class template there. 您没有不完整的类型-那里有一个类模板。 It often catches out people new to C++, but instantiations of that template with different types are (to the compiler/type system) entirely unrelated .
它通常会吸引C ++新手,但是使用不同类型的模板实例化(对于编译器/类型系统) 是完全不相关的 。
The template itself also isn't a "base class" of the instantiations - it cannot be used without supplying it's template type arguments. 模板本身也不是实例化的“基类”-如果不提供模板类型参数,则不能使用它。
As you're talking about "serializing to strings" I wonder if you're looking for the streaming operators instead - specifically streaming to string streams (see eg https://docs.microsoft.com/en-us/cpp/standard-library/overloading-the-output-operator-for-your-own-classes ). 当您谈论“序列化为字符串”时,我想知道您是否在寻找流运算符-特别是流传输到字符串流(请参见例如https://docs.microsoft.com/zh-cn/cpp/standard-库/为自己的类重载输出操作符 )。
What happens there is that you overload the << operator for your own types and the type of stream you want, eg 发生的情况是,您为自己的类型和所需的流类型重载了<<操作符,例如
std::ostringstream& operator<<(std::ostringstream& i_stream, const MyType& i_val) {
i_stream << "( " << i_val.GetValue1() << ", " << i_val.GetValue2() << " )" << std::endl;
return i_stream;
}
Then you can stream any kind of object into a string stream, as long as you've overloaded the stream operator for it. 然后,只要已为它重载了流运算符,就可以将任何类型的对象流式传输为字符串流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.