问题描述
我正在构建一个包含向量作为某些字段的自定义 cmessage。我对 int
或 double
向量没有问题,但是对于 string
向量,我收到错误消息。下面是重现问题的示例消息定义。
cplusplus {{
#include <vector>
typedef std::vector<int> IntVector;
typedef std::vector<string> StrVector;
}};
class IntVector { @existingClass; };
class StrVector { @existingClass; };
message sampleMessage extends cmessage
{
IntVector SampleIntVector;
StrVector SampleStrVector;
}
sampleMessage *msg = new sampleMessage();
vector<int> intVect = {1,2};
vector<string> stringVect;
string inputString = "dummy string";
stringVect.push_back(inputString);
msg->setSampleIntVector(intVect);
msg->setSampleStrVector(stringVect);
使用 OMNeT++ 6.0 pre10 版,在第 7 行,我收到以下错误提示 cmessage 正在等待 vector<char *>
error: no viable conversion from 'vector<std::string>' to 'const vector<char *>'
我还尝试了 OMNeT++ 5.6.2 版,但收到了不同的错误消息。为清楚起见,文件 testModel_m.cc 由 OMNeT++ 生成。
testModel_m.cc:170:13: error: use of overloaded operator '<<' is ambiguous (with operand types 'std::ostream' (aka 'basic_ostream<char>') and 'const std::__cxx11::basic_string<char>')
out << *it;
~~~ ^ ~~~
testModel_m.cc:2040:45: note: in instantiation of function template specialization 'operator<<<std::__cxx11::basic_string<char>,std::allocator<std::__cxx11::basic_string<char> > >' requested here
case 1: {std::stringstream out; out << pp->getSampleStrVector(); return out.str();}
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/basic_string.h:6416:5: note: candidate function [with _CharT = char,_Traits = std::char_traits<char>,_Alloc = std::allocator<char>]
operator<<(basic_ostream<_CharT,_Traits>& __os,^
testModel_m.cc:158:22: note: candidate function [with T = std::__cxx11::basic_string<char>]
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
如果我将向量更改为 char *
,它可以工作,但是对于我的用例,我需要一个 string
的向量,因为我在向量中搜索值并使用 char *
,效果不太好。
有没有办法将 vector<string>
字段作为自定义 cmessage 的一部分?
解决方法
错误 use of overloaded operator '<<' is ambiguous
的解决方法是在 operator<<
块内添加自己的 cplusplus {{ }}
定义,例如:
cplusplus {{
#include <vector>
typedef std::vector<int> IntVector;
typedef std::vector<std::string> StrVector;
std::ostream& operator<<(std::ostream &os,const StrVector& vec) {
std::stringstream out;
for (auto i : vec) {
out << i << ",";
}
return os << out.str();
};
}};
class IntVector { @existingClass; };
class StrVector { @existingClass; };
message sampleMessage {
IntVector SampleIntVector;
StrVector SampleStrVector;
}