微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将 vector<string> 字段添加到 cMessage

如何解决将 vector<string> 字段添加到 cMessage

我正在构建一个包含向量作为某些字段的自定义 cmessage。我对 intdouble 向量没有问题,但是对于 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;
} 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。