passing ‘const Link’ as ‘this’ argument of ‘std::string GetAttribute(std::string)’ discards qualifiers
Question
I'm getting an odd error with parts of the NS-3 API. Here is my error message:
error: passing ‘const ns3::TopologyReader::Link’ as ‘this’ argument of ‘std::string ns3::TopologyReader::Link::GetAttribute(std::string)’ discards qualifiers
And here is the code causing the issue:
TopologyReader::ConstLinksIterator iter;
int num = 0;
for (iter = topologyReader->LinksBegin (); iter != topologyReader->LinksEnd(); iter++, num++)
{
std::istringstream fromName(iter->GetFromNodeName ());
std::istringstream toName (iter->GetToNodeName ());
iter->GetToNodeName();
std::string w = "Weight";
std::string weightAttr = (iter)->GetAttribute(w); // <- error
/* snip */
}
I think it might have to do with the fact that GetAttribute(std::string)
is not a const
function, according to the documentation for TopologyReader::Link, while the other functions, GetFromNodeName(void)
and GetToNodeName(void)
are declared as const
functions. However, I'm not sure how to fix this problem.
Edit: The function signatures are as shown (from the linked documentation):
std::string ns3::TopologyReader::Link::GetFromNodeName (void) const
std::string ns3::TopologyReader::Link::GetToNodeName (void) const
std::string ns3::TopologyReader::Link::GetAttribute (std::string name)
Solution
Your analysis is correct. The obvious fix is to make GetAttribute
be a const function. Its name suggests it should be const. It might not be in your power to change that code, though.
The alternative is to find some way of getting a non-const object to call the function on. Maybe you could declare iter
as a LinksIterator
instead of a ConstLinksIterator
.
As a last resort, you could try using const_cast
to tell the compiler that it's really safe to call a non-const method on a supposedly const object.