I'm stuck. When trying to add a new element to the vector of strings inside a struct via the iterator I get this error about const qualifier:
error: passing ‘const std::vector<std::__cxx11::basic_string<char> >’ as ‘this’ argument discards qualifiers [-fpermissive]
175 | p->children.push_back("New child");
The code:
typedef struct Concept_tree
{
string id;
string name;
std::vector<string> children;
bool operator==(const Concept_tree &ct2)
{
return (id == ct2.id);
}
Concept_tree() { };
Concept_tree(string id): id(id) { };
Concept_tree(string id, string term): id(id), name(term) { };
}
Concept_tree;
namespace std
{
template<>
struct hash<Concept_tree>
{
size_t operator()(const Concept_tree &ct) const
{
return std::hash<string>()(ct.id);
}
};
}
...
std::unordered_set<Concept_tree> ct_uset;
...
string test = "id00001";
auto p = ct_uset.find(test);
p->children.push_back("New child");
I understand the cause of the error but can't deduce its exact position. Is it that the constructors are implemented improperly? Could anyone help?
You got the iterator p from an unordered_set; the contents of unordered_set are immutable (to avoid violating invariants), and the iterator returned is a const view of the elements to ensure that.
You could mark children as mutable so it can be mutated even when the Concept_tree is const (since it's not part of equality/hash computation, this might be okay). But this will make it possible to mutate children even when you want a Concept_tree to be logically const. To avoid that, you could use an unordered_map mapping just the id (immutable key) to the actual Concept_tree (mutable value) object.
Side-note: You probably want to mark your operator== as const so this is const, or make it a non-member function with both argument const per What are the basic rules and idioms for operator overloading?.
Related
I would like to use a unary function to look up a certain parameter name in a list with std::find
class Parameter {
public:
string getName() { return mName;}
//string mName;
private:
string mName;
string mType;
string mValue;
};
class Param_eq : public unary_function<Parameter, bool> {
string mName;
public:
Param_eq (const string& name) : mName(name) {}
bool operator() (const Parameter& par) const {
return (mName == par.getName());
}
};
double Config::getDouble(string& name) {
list<Parameter>::iterator iParam = find(mParamList.begin(), mParamList.end(), Param_eq(name));
double para = iParam->getDouble();
return para;
}
}
But I get the following compiler error
error C2662: 'Parameter::getName' : cannot convert 'this' pointer from 'const Parameter' to 'Parameter &'
Conversion loses qualifiers
If I make the member variable Parameter::mName public and use it instead of the member function Parameter::getName() in the return statement of Param_eq::operator() it compiles without error.
bool operator() (const Parameter& par) const {
return (mName == par.mName);
}
Why is that? Both member variable and member function are string type.
How do I get the above example to work by using a member function?
The error tells you that you are calling a non-const method on a const reference. A non-const method may modify member variables and thus violate the const constraint.
You can solve this two ways:
Don't call the method at all and access the mName variable directly:
bool operator() (const Parameter& par) const {
return (mName == par.mName);
}
Note that this does not require making mName public. This works because operator() is a member of the Parameter class. Remember that private members are accessible in any method of the class. It does not matter whether you access the private members of another instance of the same class or not.
Declare getName() to be const objects:
string getName() const { return mName;}
Note the location of the const qualifier. This tells the compiler that the method will not modify any member variables.
I have a class ConfigFile that has a getter for the SVMParams member:
cv::SVMParams gerSVMParams()
{
return *m_mapConfig["SVMParams"];
}
The code is a little bit more complicated. m_mapConfig is a
std::map<std::string, std::unique_ptr< IConfigItem > >
And IConfigItem is a template class that looks like this for SVMParams:
template<> class ConfigItem< cv::SVMParams > : public IConfigItem
{
private:
cv::SVMParams m_value;
public:
ConfigItem(const cv::SVMParams& valueIn) : m_value(valueIn) {}
operator cv::SVMParams() const
{
return m_value;
}
};
My problem is when I am trying to auto train the SVM classifier:
classifier.train_auto(trainingData, classes, cv::Mat(), cv::Mat(), configFileIn.getSVMParams());
I am getting an error of kind:
error: passing ‘const ConfigFile’ as ‘this’ argument of ‘cv::SVMParams ConfigFile::getSVMParams()’ discards qualifiers [-fpermissive]
Any suggestions of what I am doing wrong? Or is there a small bug because because the train_auto functions has no const in front of the SVMParams parameter. Or is it modifying it?
Make your function const:
cv::SVMParams gerSVMParams() const
// ^^^^^
The error is you are calling a non-const method on a const object, which the compiler rejects as being potentially unsafe. That said, your implementation is inherently non-const too since you might be inserting an object into your map, so just adding the const won't help.
What you probably want to do is:
cv::SVMParams gerSVMParams() const
// ^^^^^
{
auto it = m_mapConfig.find("SVMParams");
if (it != m_mapConfig.end()) {
return *(*it);
}
else {
return {}; // maybe?
}
}
Found the problem: I was calling the function in which I was calling the getSVMParams() with const ConfigFile&; and that was not allowed by the shared_ptr I used in the map.
Thanks all, anyway!
This question already has answers here:
cast const Class using dynamic_cast
(2 answers)
Closed 9 years ago.
I have the following classes and methods:
//Base class
class Node {
public:
virtual ~Node() {};
Node() {};
private:
// Private things for my implementation.
};
class Element : public Node {
public:
// Returns the name of the element.
const xml::String &name() const {
return eleName;
}
static bool is_Element(const Node *base) {
Element *p = NULL;
p = dynamic_cast<Element*>(base);
return (p!=NULL);
}
static const Element *to_Element(const Node *base) {
return dynamic_cast<Element*>(base);
}
private:
s_namespace eleNamespace;
xml::String &eleName;
// Private things for my implementation.
};
Here when I dynamic cast it says the following compile error. How to correct it? One method is to simple remove the const of the parameters. But I donot think that is the correct method.
oops.cpp: In static member function ‘static bool
xml::Element::is_Element(const xml::Node*)’: oops.cpp:208:44: error:
cannot dynamic_cast ‘base’ (of type ‘const class xml::Node*’) to type
‘class xml::Element*’ (conversion casts away constness) oops.cpp: In
static member function ‘static const xml::Element*
xml::Element::to_Element(const xml::Node*)’: oops.cpp:213:47: error:
cannot dynamic_cast ‘base’ (of type ‘const class xml::Node*’) to type
‘class xml::Element*’ (conversion casts away constness)
Use dynamic_cast<const Element*> instead.
You can also make your class const-correct, by implementing two different functions for a const-Argument and a non-const Argument:
static const Element *to_Element(const Node *base) {
return dynamic_cast<const Element*>(base);
}
static Element *to_Element(Node *base) {
return dynamic_cast<Element*>(base);
}
So if the caller has a non-const Node he probably also wants a non-const Element and now he can get it...
Try this:
static bool is_Element(const Node *base) {
const Element *p = NULL; // Add a const keyword here
p = dynamic_cast<const Element*>(base); // Add a const keyword here
return (base!=NULL);
}
And the same for to_Element
class Song {
public:
const string getAutherName();
}
void mtm::RadioManager::addSong(const Song& song,const Song& song1) {
if (song.getAutherName() == song1.getAutherName())
}
I get this error:
Invalid arguments ' Candidates are: std::basic_string<char,std::char_traits<char>,std::allocator<char>> getAutherName() ' - passing 'const mtm::Song' as 'this' argument of 'std::string mtm::Song::getAutherName()' discards qualifiers [- fpermissive]
Why is it using basic_string and not string! how to fix this?
Your getAutherName() function is not const, so it cannot be called through a const Song&. Change the function declaration like this:
class Song {
public:
const string getAutherName() const;
}
You are calling getAutherName() on const Songs so you need to make that method const:
const string getAutherName() const;
It isn't clear why you return a const string. Either return a string, or return a const reference to one:
const string& getAutherName() const;
string getAutherName() const;
std::string is a typedef for basic_string<char, std::char_traits<char>, std::allocator<char> >, the compiler is just expanding the typedef in the error message.
However, why the code is not working I don't know. You appear to have cut out part of your error message where the ' is.
You need to add a const qualification to getAutherName to allow it to be called on const Song objects:
//| -- Returns a `const` `string` (this is bad practice
//v because it inhibits optimization)
const string getAutherName() const;
// Can be called on a `const` ^
// `Song`. This is good practice |
// because it it allows `getAutherName()`
// to be used in more places, and it encourages
// const-correctness.
I know this sounds like a strange question, but bear with me.
I have a custom class that has some large objects which need to be returned by reference to avoid a copy.
My class looks something like this:
class csv_File {
public:
csv_File(std::string); //constructor
std::string const& access(int,int) const;
void modify_element(int column,int row ,std::string value) {
storage.at(row).at(column)=value;
}
private:
mutable std::vector < std::vector<std::string> > storage;
};
The code for access is:
string const& csv_File::access(int column,int row) const {
return storage.at(row).at(column);
}
When I try to compile this, I get an error, as it wants
csv_File::modify_element(int column,int row ,std::string value) const {}
In practice, storage is logically const, but I just need to be able to modify it once in a while. Is there a way to do this?
Also, a related question. If I call modify_element to modify an element in storage, but previously, I have returned a reference to that element using access, will the reference that was returned previously pick up the new value after the modify_element call?
After fixing up your program, and with the hint from #user763305, I suppose you have something like this (note: this program compiles, but invokes undefined behavior when run, since the storage vector is left empty):
#include <string>
#include <vector>
class csv_File {
public:
csv_File(std::string) {}
std::string const& access(int,int) const;
void modify_element(int column,int row ,std::string value) {
storage.at(row).at(column)=value;
}
private:
mutable std::vector < std::vector<std::string> > storage;
};
std::string const& csv_File::access(int column,int row) const {
return storage.at(row).at(column);
}
const csv_File& Factory() { static csv_File foo("foo.txt"); return foo; }
int main(){
const csv_File& f(Factory());
f.modify_element(1, 2, "hello");
}
and you get an error like this:
cs.cc: In function ‘int main()’:
cs.cc:24: error: passing ‘const csv_File’ as ‘this’ argument of ‘void csv_File::modify_element(int, int, std::string)’ discards qualifiers
So, you have a const object and are trying to invoke modify_element on it. Logically, this is a mistake -- you can't modify const objects!
You have, as I see it, two choices for a fix. Either you can declare the vector object mutable and the modify_element method const, or you can modify your object factory to return non-const references.
Solution 1:
...
void modify_element(int column,int row ,std::string value) const {
storage.at(row).at(column)=value;
}
...
Solution 2:
...
const csv_File& Factory() { static csv_File foo("foo.txt"); return foo; }
csv_File& RW_Factory() { static csv_File foo("foo.txt"); return foo; }
...
const csv_File& f(RW_Factory());
...
EDIT
And, yes, if you previously returned a reference to a string in your vector, and you subsequently assign a new value to that string as you do in modify_element, then the previous reference will reflect the new value.
Note that the previous reference will be invalid if you destroy the vector, erase that vector element, or do anything to cause the vector to grow beyond its previous capacity.