It seems like you want to include a switch mechanism based on the type of argument during the argument parsing process. For this to be effective, we would typically recognize each argument type (like Int, String, Bool, etc.) and operate accordingly.
To properly apply a switch mechanism based on type during parsing, you'll have to implement a type-aware system within your argument parser. One common method for this is to use polymorphism, establishing a base Arg class that Int, String, Bool, and others inherit from, as well as using a virtual method that each derived class must implement for their specific parsing behavior.
Here's a simplified version of what the mechanism might look like in pseudo code:
cpp
// This is a base class for all argument types
class Arg {
public:
virtual bool ParseValue(const std::string& arg_string) = 0; // Pure virtual function
// ... other functions and members
};
// Derived class overrides the ParseValue method for string arguments
class StringArg : public Arg {
public:
bool ParseValue(const std::string& arg_string) override {
value_ = arg_string;
return true;
}
// ... members like value_
};
// Derived class overrides the ParseValue method for int arguments
class IntArg : public Arg {
public:
bool ParseValue(const std::string& arg_string) override {
try {
value_ = std::stoi(arg_string);
return true;
} catch(const std::invalid_argument&) {
return false; // Parsing failed, invalid input
}
}
// ... members like value_
};
// And similar for BoolArg or any other specific argument types you need
class ArgParser {
std::vector<Arg*> args_; // Holds all argument instances
public:
// ...
bool Parse(std::vector<std::string> args) {
// --y=123 or --name=example
for (const auto& arg : args) {
std::string key = /* extract key from arg */;
std::string value = /* extract value from arg */;
// Find the corresponding Arg object for the key
Arg* arg_obj = FindArgByKey(key);
if (arg_obj) {
if (!arg_obj->ParseValue(value)) {
// Handle parsing error
}
}
}
return true;
}
private:
Arg* FindArgByKey(const std::string& key) {
// Search through args_ to find and return the Arg corresponding to key
// If not found, return nullptr
}
// ...
};
User
ude enum Type
Assistant
To use an enum to specify argument types within your argument parser, you can create an enum to represent the different types of arguments your parser can handle, and then utilize this to drive the parsing logic.
Here is how you could integrate an enum for argument types into your existing argument parser's structure:
First, define the enum for your argument types:
cpp
namespace ArgumentParser {
enum class Type {
INT,
STRING,
BOOL,
// Add other argument types as needed.
};
// ... (rest of your existing code)
}
Then, modify the Args classes to include a Type variable to store the type of argument:
cpp
namespace ArgumentParser {
class Args {
public:
// Existing members and methods
virtual Type GetType() const = 0; // Add this pure virtual function
};
class IntArg : public Args {
public:
// Existing members and methods
Type GetType() const override {
return Type::INT;
}
};
class StringArg : public Args {
public:
// Existing members and methods
Type GetType() const override {
return Type::STRING;
}
};
class BoolArg : public Args {
public:
// Existing members and methods
Type GetType() const override {
return Type::BOOL;
}
};
// ... (rest of your existing code)
}
Inside your Parse function, you can now switch on the Arg type to determine how to parse the argument:
cpp
User
class Int : public Args {
Type GetType() const override {
return Type::INT;
}
void StoreValues(std::vector& store_values);
void AddStoreValues(const std::string value);
bool GetFlagStoreValues();
The error message you're seeing, "identifier 'Type' is not defined" (C/C++(20)), indicates that the compiler cannot find the definition for Type within the scope where you're trying to use it. This usually happens due to issues with the declaration scope, missing includes, or misnamed identifiers.
To resolve this, you need to ensure that:
The Type enum is defined before its use.
The Type enum is within the correct namespace and is accessible where it's being used.
Here's a very basic example setup assuming Type is declared within the ArgumentParser namespace:
cpp
// Args.h or Args.cpp, depending on your project structure
#pragma once
#include <vector>
#include <string>
namespace ArgumentParser {
// Declare the enum Type inside the namespace where Args is also declared
enum class Type {
INT,
STRING,
BOOL
// Add other argument types as needed.
};
class Args {
public:
virtual ~Args() {}
virtual Type GetType() const = 0; // Pure virtual function
// ... other functions and members
};
class Int : public Args {
public:
Type GetType() const override {
return Type::INT;
}
void StoreValues(std::vector<int>& store_values);
void AddStoreValues(const std::string value);
bool GetFlagStoreValues();
// Your class's member variables and functions
// ...
};
// ... other derived classes and members
} // End of ArgumentParser namespace
If you're separating your classes into different header files, you need to make sure the enum Type is included before the definition of Int. You can achieve this by having the Type enum in its header file and including that file in the headers for your Int, String, and Bool classes or by ensuring the header files are included in the correct order.
For example, if Type enum is in Types.h:
cpp
// Types.h
#pragma once
namespace ArgumentParser {
// The Type enum
enum class Type {
INT,
STRING,
BOOL
// ...
};
} // namespace ArgumentParser
Then in your Int.h you would include Types.h:
cpp
// Int.h
#pragma once
#include "Types.h" // Include the Types.h header where the Type enum is defined
#include "Args.h" // Include the base class header
// ... The rest of your Int class declaration
Usually, when coming across such errors, double-check your usage and declaration of namespaces and verify that all necessary header files are properly included where they are required.
The error message "identifier 'args_' is not defined" (C/C++(20)) suggests that the args_ variable has not been declared in the current scope or is not included in the file where you are trying to use it.
The args_ variable looks like it is intended to be a member of the ArgParser class that holds a collection of Args objects, each one representing a command line argument that your parser can handle.
To resolve the issue, make sure you declare the args_ member variable inside your ArgParser class. It should be a container (like std::vector) that holds pointers or smart pointers to the base Args class. Following are the changes you need to do in your code:
In the ArgParser class definition, add the args_ member:
cpp
// In ArgParser.h
namespace ArgumentParser {
class ArgParser {
// ... your other members
// Member variable that holds the argument objects
std::vector<Args*> args_;
// ... other methods and members of ArgParser
};
// ... other definitions
} // namespace ArgumentParser
Then, you need to correctly reference this member in the Parse method and also ensure that you have the appropriate logic to use your Args objects afterwards.
Make sure to properly manage the memory for these dynamically allocated objects. C++ provides smart pointers, like std::unique_ptr or std::shared_ptr that automatically handle memory management:
cpp
std::vector<std::unique_ptr<Args>> args_;
In your AddStringArgument, AddIntArgument, and other similar methods where you are adding arguments to the parser, you should be storing them in args_ correctly:
Repeat the pattern for other argument types, making sure to store them in your args_ member.
Finally, in your Parse method, iterate over args_ and parse each argument accordingly:
cpp
bool ArgParser::Parse(std::vector<std::string> cmdline_args) {
// ... your existing parse logic, but correctly using args_ now
for (auto& arg : args_) {
switch (arg->GetType()) {
// ... your switch cases
}
}
// ...
}
This should resolve the error you're encountering as long as the rest of your code has been set up to recognize and use the args_ member variable properly.
User
Args& ArgParser::AddIntArgument(const std::string number) {
Args* int_val = new Args(number);
all_.push_back(int_val);
return *int_val;
}использование объекта абстрактного типа класса "ArgumentParser::Args" не допускается:C/C++(322)
ArgParser.cpp(164, 29): функцию "ArgumentParser::Args::GetType" является чистой виртуальной функцией
class ArgumentParser::Args
Assistant
The error message you are encountering, "use of abstract class type 'ArgumentParser::Args' is not permitted" (C/C++(322)), indicates that you are trying to instantiate an object of an abstract class. In C++, an abstract class is a class that has at least one pure virtual function. You cannot create instances of an abstract class directly, you can only instantiate derived classes that properly override all the pure virtual functions.
From the code snippet you provided, it seems like you're trying to create an instance of Args which is intended to be an abstract base class. You should be creating an instance of a derived class, such as IntArg or a similar class specifically meant to handle integer arguments and which overrides the GetType() method (or any other pure virtual methods).
Here is how you'd typically create an AddIntArgument function that instantiates a hypothetical IntArg class:
cpp
class IntArg : public Args {
public:
IntArg(const std::string& number) {
// Constructor functionality to handle 'number'
}
Type GetType() const override {
return Type::INT;
}
// Implement other required member functions
};
Args& ArgParser::AddIntArgument(const std::string& number) {
IntArg* intArg = new IntArg(number); // Create an instance of IntArg, not Args
all_.push_back(intArg);
return *intArg;
}
Ensure that IntArg fully implements all pure virtual functions from the Args base class. Until all pure virtual functions are overridden by derived classes, those derived classes are abstract as well.
Remember also to pay attention to memory management when using raw pointers (new). You should ensure that memory is released appropriately, preferably using smart pointers (e.g., std::unique_ptr, std::shared_ptr) instead of raw pointers. This helps in automatic release of the resource when it's no longer needed and helps avoiding memory leaks.
Here's how to use std::unique_ptr for memory management in your ArgParser class:
cpp
User
Args& ArgParser::AddIntArgument(const std::string number) {
Int* int_val = new Int(number);
all_.push_back(int_val);
return *int_val;
}
#pragma once
#include
#include
It looks like there's an issue with the way you're attempting to declare the constructor for the Int class. The error message suggests that the specific constructor cannot be accessed, and this could be due to multiple reasons such as incorrect signature, private access specifier, or the definition being provided in a separate compilation unit without proper linkage.
To address the constructor visibility issue in Int class, ensure the constructor is declared public:
cpp
namespace ArgumentParser {
class Int : public Args {
public:
explicit Int(const std::string& number) {
// It's better practice to use the initializer list,
// unless you need to handle exceptions or complex logic inside the constructor.
int_val_ = std::stoi(number);
}
Type GetType() const override {
return Type::INT;
}
// ... Rest of your code
};
} // namespace ArgumentParser
Ensure that the Int constructor is public, and there are no typos or mismatched parameter types. In this case, use explicit when declaring the constructor that takes a single argument to prevent accidental implicit conversions. Also, always use the initializer list where possible for initialization. Since std::stoi() can throw an exception (std::invalid_argument or std::out_of_range) if the input string does not represent a valid integer, you might want to handle that situation inside your constructor or before calling it:
cpp
// In ArgParser class
Args& ArgParser::AddIntArgument(const std::string& number) {
try {
Int* int_val = new Int(number); // Ensure correct construction without exception
all_.push_back(int_val);
return *int_val;
} catch (const std::invalid_argument& e) {
// Handle exception if string cannot be converted to an integer
} catch (const std::out_of_range& e) {
// Handle exception if converted integer is out of range
}
}
User
ArgParser& ArgParser::AddStringArgument(const char short_param, const std::string param) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
all_->push_back(*str);
return this;
}оператор -> или -> применяется к "std::__1::vector<ArgumentParser::Args *, std::__1::allocator<ArgumentParser::Args *>>", а не к типу указателяC/C++(3364)
std::_1::vector<ArgumentParser::Args *> ArgumentParser::ArgParser::all
Assistant
The error you are encountering suggests that all_ in the ArgParser class is dereferenced using the -> operator, which assumes that all_ is a pointer. This is incorrect because all_ is a vector of pointers, not a pointer itself. The -> operator is used with pointers to access an object's members directly, while a vector's elements are accessed using the [] operator or iterators.
Given that all_ is a std::vector<Args*>, you should be adding a pointer to str to the all_ vector using push_back, without dereferencing the pointer. Moreover, you must also fix the vector's syntax from all_->push_back(*str) to all_.push_back(str).
Here's the corrected code snippet:
cpp
ArgParser& ArgParser::AddStringArgument(const char short_param, const std::string param) {
String* str = new String(short_param, param); // Construct String with short_param and param
all_.push_back(str); // Add the pointer to the vector
return *this;
}
Remember that this will push the raw pointer into the vector, and you must manage the memory allocated by new. It is suggested to use smart pointers to avoid memory leaks. Below is how you could use std::unique_ptr for this purpose:
First, change the all_ vector to store std::unique_ptr<Args>:
cpp
// Inside your ArgParser class
std::vector<std::unique_ptr<Args>> all_;
Then you can modify the AddStringArgument method to use smart pointers:
cpp
ArgParser& ArgParser::AddStringArgument(const char short_param, const std::string param) {
auto str = std::make_unique<String>(short_param, param); // Use std::make_unique to allocate
all_.push_back(std::move(str)); // Transfer ownership to the vector
return *this;
}
Do not forget to include <memory> and adapt the rest of your code where necessary to work with std::unique_ptr instead of raw pointers.
Ensuring these modifications will prevent the error and should lead you towards better memory management practices in modern C++.
User
std::vector<std::unique_ptr> all_; do not use std::unique_ptr
Assistant
If you have decided not to use std::unique_ptr and instead manage the memory manually using raw pointers, you must remember to deal with the deallocation of the memory yourself to prevent memory leaks.
Given that your all_ vector is a vector of raw pointers to Args, you can push pointers into it as follows:
cpp
// Inside your ArgParser class definition:
std::vector<Args*> all_;
// Inside your ArgParser member function:
ArgParser& ArgParser::AddStringArgument(const char short_param, const std::string param) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
all_.push_back(str); // Add the pointer to the vector
return *this;
}
Make sure to release the memory associated with your dynamically allocated objects when the ArgParser object is destroyed or when you no longer need those arguments. This is typically done in the destructor of the ArgParser class:
cpp
ArgParser::~ArgParser() {
for (Args* arg : all_) {
delete arg; // Deallocate each argument
}
}
It is crucial that whenever you add, remove, or replace elements in all_, you also take care of the memory management accordingly. This can become complex and error-prone, which is why smart pointers are recommended. However, if you are constrained to using raw pointers, be very careful and ensure that you have no memory leaks and no dangling pointers.
Here's a summary of the steps you must follow when only using raw pointers:
When adding a pointer, use new to allocate it.
Store the raw pointer in a container such as std::vector<Args*>.
When the container is destroyed, or you remove an element, use delete to deallocate the memory.
Ensure exception safety: if an exception may be thrown after allocating memory but before the pointer is added to the container, the memory might not be released. Consider using a try-catch block to handle such scenarios, or better yet, design your code in a way that allocation and container insertion are done atomically (for instance, using smart pointers).
/*
Функция принимает в качество аргумента строку, разделяет ее по "пробелу"
и возвращает вектор полученных слов
*/
std::vectorstd::string SplitString(const std::string& str) {
std::istringstream iss(str);
The error message indicating that "class 'ArgumentParser::ArgParser' does not contain a member 'Default'" suggests that you're trying to call a method named Default on an instance of ArgParser, but no such method exists within the ArgParser class.
From your test cases, it looks like you're trying to call Default on the object returned by AddStringArgument and AddFlag, which should be an object of type Args, not ArgParser.
To resolve the issue, each specific argument class (Int, String, Bool) needs to provide an implementation of the Default method so that it can be chained properly after calling, for instance, AddStringArgument.
Here's an example of how you might correct the String class to include the Default method:
cpp
class String : public Args {
public:
// ... other members and methods ...
String& Default(const std::string& value) {
default_value_ = value;
// Add any additional logic needed for setting the default value
return *this;
}
// ... rest of the String class implementation...
};
With this change, the AddStringArgument method should return a reference to String rather than Args:
cpp
String& ArgParser::AddStringArgument(const char short_param, const std::string param) {
auto str = new String(short_param, param);
all_.push_back(str); // assuming that all_ is a std::vector<Args*>
return *str; // returning a reference to the String object
}
Make sure that similar changes are made for other argument types, so they all have the Default method which returns an appropriate self-reference for chaining calls.
For the Bool class, since Default should be dealing with a bool value, not a std::string, you'd have it like this:
/*
Функция принимает в качество аргумента строку, разделяет ее по "пробелу"
и возвращает вектор полученных слов
*/
std::vectorstd::string SplitString(const std::string& str) {
std::istringstream iss(str);
The error message you're getting indicates that the StoreValues function is missing from your Args base class. The error occurs because you have declared and defined StoreValues in your Int class, but given the way you're trying to use it, it seems like you expect it to be available from the Args base class.
Based on the test suite and method chaining in your ArgParser class (specifically with AddIntArgument), it appears that you want to have StoreValues to be a member function of Args or have similar functionality available in Args.
Here's how to correct this situation:
If all derived classes (Int, String, Bool) require the StoreValues functionality, you should declare this function as a virtual member of Args and provide default behavior or make it pure virtual (forcing derived classes to implement it) if there is no sensible default behavior.
Given your usage, it seems like StoreValues should be in classes that deal with values that can be stored (like Int and String), and may not make sense in Bool which may instead have StoreValue function in singular. You might therefore opt not to include it in the Args base class but instead only in the derived classes that need it.
You need to rectify the incorrect static_cast usage in GetIntValue and AddIntArgument member functions. You should not be casting Args objects to String in GetIntValue.
Make sure that when you are dynamically casting, you respect the actual types. For instance, it’s not correct to first perform a static_cast to String* and then immediately to Int*. This is evident in the code where you have the following line that is syntactically incorrect as it stands:
cpp
Int* arg = static_cast<Int*>(arg);
Here is a quick fix according to point number 1, if you were to declare StoreValues in Args:
The error message "use of abstract class type 'ArgumentParser::String' is not permitted" (C/C++(322)) suggests that the String class has been declared as an abstract class because it inherits from the Args base class which contains at least one pure virtual function, specifically the StoreValues method.
Let's address how to correctly implement or override the pure virtual functions from the Args base class in order to avoid String (and other derived classes like Int and Bool) becoming an abstract class.
Firstly, in your base class Args, the existence of StoreValues as a pure virtual function requires any concrete class that inherits from Args to provide a definition for this function or otherwise the derived class would be considered abstract:
cpp
// In Args class definition
class Args {
public:
// ... other members ...
virtual void StoreValues(std::vector<int>& store_values) = 0; // pure virtual function
// ... other members ...
};
To fix this, you need to override StoreValues in your String and other derived classes. Since it seems that StoreValues is specific to storing integer values, you may need to reconsider the design. If the String class doesn't need this function, you might not want to define it as a pure virtual function in Args. Instead, you could provide a default implementation or simply remove the function in case it's not applicable to all derived classes.
The error message you're receiving indicates that the class String, which inherits from the abstract class Args, cannot be instantiated because it does not override the pure virtual function StoreValues. To resolve this, you need to provide an implementation of this function in the String class.
It appears that you use StoreValues to store a list of integer values for the Int class. Implementing this in the String class, which deals with strings, doesn't make sense unless you're operating on arguments where multiple string values are expected and you want to store them in a list.
If the String class isn't meant to store multiple values, you have a few design options:
Remove the pure virtual declaration in Args: If StoreValues is only relevant for Int, do not declare it as a pure virtual method at the Args level.
Provide a dummy implementation in String: If all derived classes must override StoreValues but its behavior isn't applicable or necessary for String, you can provide a dummy or default implementation that does nothing or throws an exception.
Use a common data structure for values: Adjust the design so that StoreValues makes more sense in all derived types. For example, use a std::vector<std::string> to accommodate storing multiple strings, integers, and even string representations of boolean flags.
Here's how you might implement the second option:
cpp
// Inside the String class definition
class String : public Args {
public:
// ... existing methods ...
// You must override this function to avoid String being abstract.
// Because storing values is meaningful primarily for Int,
// you'll provide a dummy implementation.
void StoreValues(std::vector<int>& store_values) override {
// Do nothing, or throw an exception if this function should not be called on String objects.
// throw std::runtime_error("StoreValues not applicable for String");
}
};
User
store values should be in Int class
Assistant
If the method StoreValues should only be in the Int class and doesn't make sense in the String or Bool classes, you need to adjust your design accordingly. Since StoreValues is a pure virtual method in your base Args class, all classes deriving from Args are required to implement it, making them abstract if they don't.
In this case, you should remove the pure virtual StoreValues method from the Args base class and only declare and define it within the Int class where it is relevant. You should also remove or comment out any code from other derived classes (String, Bool) that incorrectly override StoreValues.
Here are the changes you need to make:
Remove the pure virtual declaration of StoreValues from Args.
cpp
// In Args class definition
class Args {
// ... other members ...
// Remove the following line:
// virtual void StoreValues(std::vector<int>& store_values) = 0;
// ... other members ...
};
Int class should be the only class that implements StoreValues.
cpp
// In Int class definition
class Int : public Args {
public:
// ... existing methods ...
// Implement the StoreValues method specific to Int class.
void StoreValues(std::vector<int>& store_values) override {
store_values_ = &store_values;
flag_store_values_ = true;
}
// ... rest of the Int class ...
};
Since StoreValues is no longer a part of the Args interface, situations where you might have called it whether or not it made sense now need to be handled differently. For example, in your Parse method where you iterate over different type of arguments, you need to check the argument type before attempting to store its values. This means that you won't use polymorphism here but rather a type-specific logic:
The error "member function declared with 'override' does not override a base class member" (C/C++(1455)) is suggesting that the StoreValues member function in the Int class is marked with the override specifier, but there is no function with the same signature in the base class (Args) for it to override.
This can happen if StoreValues is either not declared at all in the base class, or it is declared with a different signature (e.g., different parameters or const-qualification).
To resolve this error, you need to make sure of the following:
The function StoreValues must be declared in the base class Args if you want classes that derive from it to override this function. Since it seems you want StoreValues to be only in the Int class, you should not declare it in the Args class, and you should not use the override keyword in the Int class.
If StoreValues is intended to be common across all derived classes of Args, ensure that you declare it in Args with the exact same signature as used in the Int class so that the override is valid.
Here's how you can modify your code:
If StoreValues is unique to Int and not part of the Args interface, remove the override specifier:
cpp
// In Args class remove any declaration of StoreValues
// In Int class definition
class Int : public Args {
public:
// ... other member functions ...
// Remove 'override' if there is no such function in the base class Args
void StoreValues(std::vector<int>& store_values) {
store_values_ = &store_values;
flag_store_values_ = true;
}
// ... rest of the Int class...
};
If StoreValues is meant to be a part of the Args interface, declare it in Args like this:
To resolve the issue where StoreValues should only be in the Int class and not part of the Args interface, you will need to take several steps:
Remove the StoreValues method declaration from the Args class to ensure that it is no longer considered an interface that all derived classes must implement.
Ensure the StoreValues method is only implemented in the Int class since it is the only class where this method makes sense.
Modify your Parse method and any other methods accordingly to ensure that they only call StoreValues on instances of the Int class.
Here's how you can adjust your code:
Step 1: Remove StoreValues from the Args class.
cpp
class Args {
// ... other members ...
// Remove the StoreValues declaration
~Args() {};
// ... rest of the members ...
};
Step 2: Implement StoreValues only within the Int class declaration.
cpp
class Int : public Args {
// ... other members ...
void StoreValues(std::vector<int>& store_values) {
store_values_ = &store_values;
flag_store_values_ = true;
}
// ... rest of the members ...
};
Step 3: Update your code that utilizes StoreValues. Here's an example of how you might perform a dynamic_cast to check if an Args* is actually an Int* and call StoreValues accordingly.
Within the Parse method, modify the code that handles Args* pointers:
cpp
bool ArgParser::Parse(std::vector<std::string> args) {
// ... other code ...
for (auto& arg : all_) {
if (arg->GetType() == Type::INT) {
Int* intArg = dynamic_cast<Int*>(arg);
if (intArg) {
std::vector<int> values;
// Now you can safely call StoreValues because you've checked the type.
intArg->StoreValues(values);
}
}
}
// ... other code ...
}
User
Int& ArgParser::AddIntArgument(const std::string number) {
String* int_val = new String();
int_val->param_ = number;
all_.push_back(int_val);
return ;
} what should I return if #pragma once
#include
#include
In the AddIntArgument member function of the ArgParser class, you are trying to create a new instance of a String instead of Int. This is incorrect as per both the function name and expected behavior; it should be creating an instance of Int.
Once you create the correct type (an Int object), since the AddIntArgument function specifies a return type of Int&, you should return a reference to the Int object that you just created and added to the all_ vector.
Here's how you can correct and implement the AddIntArgument function:
cpp
Int& ArgParser::AddIntArgument(const std::string& number) {
// Create a new 'Int' object using 'new'
Int* int_val = new Int();
// Any additional setup of 'Int' object (like initializing members, etc.)
// No such members exist yet based on your provided code, so this step is skipped
// Add the new 'Int' object to the 'all_' member of 'ArgParser'
all_.push_back(int_val);
// Return the reference to the new 'Int' object
return *int_val;
}
Now going back to the Args class and the derived classes, ensure that they all provide overrides for all the virtual functions declared in Args. For example, you must implement GetType() in both String and Int classes because it is a pure virtual function in Args:
cpp
class String : public Args {
public:
// Implementing GetType as per requirement for derived classes
Type GetType() const override {
return Type::STRING;
}
// Other members specific to String...
};
class Int : public Args {
public:
// Implementing GetType as per requirement for derived classes
Type GetType() const override {
return Type::INT;
}
// Other members specific to Int...
};
Notice that I have removed the number_ and numer_ members, and other members that aren't essential based on the code you provided. They might be part of your implementation details which you need to handle in the constructors or other member functions specific to handling integers.
Remember, you should manage the memory for the dynamically allocated objects properly. Ensure to delete them in the ArgParser destructor to prevent memory leaks. If you decide to use modern C++ techniques such as smart pointers, this memory management becomes automatic and safer.
It appears that there is a conceptual misunderstanding about how to use the classes String and Int in the context of argument parsing. The Int class should presumably be used to handle and store integer arguments, while the String class should be responsible for string arguments.
The specific problem in the provided AddIntArgument method is an incorrect attempt to create an instance of the String class where an Int instance was expected:
cpp
Int& ArgParser::AddIntArgument(const std::string number) {
String* int_val = new String(); // Incorrect - should be Int class
// Operations intended for Int, but using a String instance?
all_.push_back(int_val);
return ; // No return value specified!
}
To solve this problem, you should create an instance of Int instead of String, and ensure that any attributes you wish to set are actually present in the Int class, then return a reference to the newly created Int object:
cpp
Int& ArgParser::AddIntArgument(const std::string& number) {
// Create a new Int object
Int* int_val = new Int();
// Assume that Int has a field to store the number as a string (TBD if you need to parse it to an actual int)
// The 'number_' field doesn't exist on `Int` in your current class definition
// You should add it if you want to use it like this:
int_val->number_ = number;
// Add new object to the vector of Args pointers
all_.push_back(int_val);
// Return a reference to the newly created object
return *int_val;
}
Before this can work, you need to ensure that the Int class has appropriate fields and methods to set and get the numeric parameter value. For example:
In the Parse method, you iterate over each argument string, separate their keys and values, find the corresponding Arg object, and then call its ParseValue method with the value string. Each derived class will provide its own implementation on how to parse their respective value strings.
This setup allows you to have a clear separation between the functionality for each type of argument and an easier mechanism to handle new argument types you might want to add in the future. Remember that this example is quite abstract and simple, so you'll have to adapt it to your particular code structure and requirements.
namespace ArgumentParser {
bool ArgParser::Parse(std::vector<std::string> args) {
// Argument parsing logic here
for (auto& arg : args_) {
switch (arg->GetType()) {
case Type::INT: {
// Parse as an integer
IntArg* intArg = static_cast<IntArg*>(arg);
// Parsing logic for integer arguments.
break;
}
case Type::STRING: {
// Parse as a string
StringArg* strArg = static_cast<StringArg*>(arg);
// Parsing logic for string arguments.
break;
}
case Type::BOOL: {
// Parse as a boolean
BoolArg* boolArg = static_cast<BoolArg*>(arg);
// Parsing logic for boolean arguments.
break;
}
// Handle other case types as needed.
}
}
// Further logic ...
return true; // Return based on your parsing logic.
}
// ... (rest of your existing code)
}
With this setup, your ArgParser can now differentiate between argument types using the enum Type and handle each argument type's parsing appropriately.
Please be mindful of object slicing if your Args objects are allocated polymorphically; you should use pointers or references when dealing with polymorphic objects. Moreover, don't forget to properly manage the memory if you're using dynamic allocation - consider using smart pointers like std::unique_ptr or std::shared_ptr for automatic memory management.
bool ArgParser::Parse(std::vector<std::string> args) {
if (all_.empty() && args.size() == 1) {
return true;
}
int count = 0;
for (int i = 0; i < args.size(); ++i) {
for (auto& arg : args_) {
switch (arg->GetType()) {
case Type::INT: {
// Parse as an integer
IntArg* intArg = static_cast<IntArg*>(arg);
// Parsing logic for integer arguments.
break;
}
case Type::STRING: {
// Parse as a string
StringArg* strArg = static_cast<StringArg*>(arg);
// Parsing logic for string arguments.
break;
}
case Type::BOOL: {
// Parse as a boolean
BoolArg* boolArg = static_cast<BoolArg*>(arg);
// Parsing logic for boolean arguments.
break;
}
// Handle other case types as needed.
}
}
std::string origin_param = "--" + all_[j]->GetParam() + "=";
std::string origin_short_param = "-";
origin_short_param.push_back(all_[j]->GetShortParam());
origin_short_param += "=";
if (args.size() == 1 && !all_[j]->GetDefaultValue().empty()) {
all_[j]->PutValue(all_[j]->GetDefaultValue());
++count;
} else if (!all_[j]->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) {
all_[j]->PutValue(args[i].substr(origin_param.length(), args[i].length()));
if (all_[j]->GetFlagStoreValue()) {
all_[j]->AddStoreValue(all_[j]->GetValue());
}
++count;
} else if (all_[j]->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) {
all_[j]->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
if (all_[j]->GetFlagStoreValue()) {
all_[j]->AddStoreValue(all_[j]->GetValue());
}
++count;
} else if (all_[j]->GetFlagMultiValue()) {
if (args[i].substr(0, origin_param.length()) == origin_param) {
all_[j]->PutValue(args[i].substr(origin_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
} else if (all_[j]->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) {
all_[j]->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
}
if (args[i][0] == '-' && all_[j]->GetFlagStoreValues()) {
all_[j]->AddStoreValues(all_[j]->GetValue());
all_[j]->AddAllValues(all_[j]->GetValue());
}
}
std::string origin_flag = "--" + all_[j]->GetFlag();
std::string origin_help = "--" + all_[j]->GetHelp();
std::string origin_short_help = "-";
origin_short_help.push_back(all_[j]->GetShortHelp());
if (all_[j]->GetIsFlag()) {
if (args[i].substr(0, origin_flag.length()) == origin_flag) {
if (all_[j]->GetFlagStoreFlag()) {
all_[j]->AddStoreFlag(true);
}
++count;
} else if (args[i][0] == '-' && args[i][1] != '-' && args[i].length() > 2) {
for (int z = 1; z < args[i].length(); ++z) {
if (args[i][z] == all_[j]->GetShortFlag()) {
if (all_[j]->GetFlagStoreFlag()) {
all_[j]->AddStoreFlag(true);
}
++count;
}
}
}
} else if (all_[j]->GetFlagPositional()) {
int count_len = 0;
for (int k = 0; k < args[i].length(); ++k) {
if (!std::isdigit(args[i][k])){
break;
} else {
++count_len;
}
}
if (count_len == args[i].length()) {
all_[j]->PutValue(args[i]);
all_[j]->MultiArgsCount();
if (all_[j]->GetFlagStoreValues()) {
all_[j]->AddStoreValues(all_[j]->GetValue());
all_[j]->AddAllValues(all_[j]->GetValue());
}
}
} else if (args[i].substr(0, origin_help.length()) == origin_help || args[i].substr(0, origin_short_help.length()) == origin_short_help) {
all_[j]->FlagHelp();
++count;
}
}
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetMultiArgsCount() > 0) {
++count;
}
if (all_[i]->GetFlagDefaultFlag()) {
++count;
}
if (all_[i]->GetMultiArgsCount() > 0 && all_[i]->GetMinArgsCount() > all_[i]->GetMultiArgsCount()) {
return false;
}
}
if (count == all_.size()) {
return true;
} else {
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetFlagHelp()) {
return true;
}
}
return false;
}
}
ArgParser& ArgParser::AddStringArgument(const std::string param) {
String* str = new String();
str->param_ = param;
all_->push_back(*str);
return *this;
}
ArgParser& ArgParser::AddStringArgument(const char short_param, const std::string param) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
all_->push_back(*str);
return *this;
}
ArgParser& ArgParser::AddStringArgument(const char short_param, const std::string param, const std::string description) {
String* str = new String();
str->param_ = param;
all_->push_back(*str);
str->Description(description);
return *this;
}
std::string ArgParser::GetStringValue(const std::string param) {
for (int i = 0; i < (all_).size(); ++i) {
if (static_cast<String*>(all_[i])->param_ == param) {
return static_cast<String*>(all_[i])->GetValue();
}
}
}
Args& ArgParser::AddIntArgument(const std::string number) {
Args* int_val = new Args(number);
all_.push_back(int_val);
return *int_val;
}
Args& ArgParser::AddIntArgument(const std::string numer, const std::string description) {
Args* int_val = new Args(numer);
all_.push_back(int_val);
int_val->Description(description);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param) {
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetParam() == param) {
int value = std::stoi(all_[i]->GetValue());
return value;
}
}
}
Args& ArgParser::AddIntArgument(const char short_param, const std::string param) {
Args* int_val = new Args(short_param, param);
all_.push_back(int_val);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param, const int ind) {
if (all_[ind]->GetParam() == param) {
return all_[ind]->GetIndexedValue(ind);
}
}
Args& ArgParser::AddFlag(const char short_flag, const std::string flag) {
Args* new_flag = new Args();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
return *new_flag;
}
Args& ArgParser::AddFlag(const char short_flag, const std::string flag, const std::string description) {
Args* new_flag = new Args();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
Args& ArgParser::AddFlag(const std::string flag, const std::string description) {
Args* new_flag = new Args();
new_flag->AddFlag(flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
bool ArgParser::GetFlag(const std::string flag) {
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetFlag() == flag) {
return true;
}
}
return false;
}
bool ArgParser::Help() {
return true;
}
Args& ArgParser::AddHelp(const char short_help, const std::string help, const std::string description) {
Args* new_help = new Args();
new_help->Help(short_help, help);
new_help->Description(description);
all_.push_back(new_help);
return *new_help;
}
std::string ArgParser::HelpDescription() {
std::cout << "My Parser\n";
std::cout << "Some Description about program\n\n";
std::cout << "-i, --input=<string>, File path for input file [repeated, min args = 1]\n";
std::cout << "-s, --flag1, Use some logic [default = true]\n";
std::cout << "-p, --flag2, Use some logic\n";
std::cout << " --number=<int>, Some Number\n\n";
std::cout << "-h, --help Display this help and exit\n";
}
}идентификатор "args_" не определенC/C++(20)
// In the ArgParser class definition
std::vector<std::unique_ptr<Args>> all_;
Args& ArgParser::AddIntArgument(const std::string& number) {
std::unique_ptr<IntArg> intArg = std::make_unique<IntArg>(number);
all_.push_back(std::move(intArg));
return *all_.back();
}
Notice how we're using std::make_unique<IntArg>(number) to create a std::unique_ptr that owns an IntArg object, and we use std::move to transfer ownership to the all_ vector. The return statement returns a reference to the Args object contained in the newly added unique_ptr. This way, the memory is managed automatically, and you won't run into issues with memory leaks.
};"ArgumentParser::Int::Int(std::__1::string number)" (объявлено в строке 63 из "/Users/alishashelby/Desktop/labwork4-alishashelby/lib/Arguments.h") недоступноC/C++(330)
inline ArgumentParser::Int::Int(std::__1::string number)
и другие перегрузки (2)
If you are defining the Int constructor in a separate source file, ensure it matches exactly with the declaration in the header file and that the source file is correctly part of the compilation units.
Lastly, regarding memory management, it would again be wise to switch to smart pointers like std::unique_ptr to automatically manage the lifetime and prevent memory leaks. Here is the previous suggestion on how to use smart pointers in your ArgParser:
cpp
// In ArgParser class definition
std::vector<std::unique_ptr<Args>> all_;
// In the ArgParser::AddIntArgument method
Args& ArgParser::AddIntArgument(const std::string& number) {
auto int_arg = std::make_unique<Int>(number);
Args& arg_ref = *int_arg; // Get the reference before ownership transfer
all_.push_back(std::move(int_arg)); // Transfer ownership to the all_ member
return arg_ref; // Return the reference to the newly created arg
}
Make sure to include <memory> and adjust any other parts of your code that handle the all_ collection since it would now be storing std::unique_ptr<Args> instead of raw pointers.
TEST(ArgParserTestSuite, HelpStringTest) {
ArgParser parser("My Parser");
parser.AddHelp('h', "help", "Some Description about program");
parser.AddStringArgument('i', "input", "File path for input file").MultiValue(1);
parser.AddFlag('s', "flag1", "Use some logic").Default(true);
parser.AddFlag('p', "flag2", "Use some logic");
parser.AddIntArgument("numer", "Some Number");
code
ASSERT_TRUE(parser.Parse(SplitString("app --help")));
// Проверка закоментирована намеренно. Ождиается, что результат вызова функции будет приблизительно такой же,
// но не с точностью до символа
/*ASSERT_EQ(
parser.HelpDescription(),
"My Parser\n"
"Some Description about program\n"
"\n"
"-i, --input=<string>, File path for input file [repeated, min args = 1]\n"
"-s, --flag1, Use some logic [default = true]\n"
"-p, --flag2, Use some logic\n"
" --number=<int>, Some Number\n"
"\n"
"-h, --help Display this help and exit\n"
);*/
};класс "ArgumentParser::ArgParser" не содержит члена "Default"C/C++(135)
cpp
class Bool : public Args {
public:
// ... other members and methods ...
Bool& Default(bool value) {
default_flag_ = value;
flag_default_flag_ = true;
return *this;
}
// ... rest of the Bool class implementation...
};
This way, the Default method is chaining correctly and is a member of the String, Int, and Bool classes, rather than ArgParser.
Make sure the Default method is properly implemented in all argument classes to match their specific needs, whether it be a boolean value or a string.
In your ArgParser, for chaining methods from the Args children, you must ensure that AddStringArgument, AddIntArgument, and AddFlag return String&, Int&, and Bool& respectively, not Args&. Each of these methods should add the newly created object to all_ and return a reference to it.
Here's a code adjustment to the AddIntArgument:
cpp
Int& ArgParser::AddIntArgument(const std::string& number) {
auto intArg = new Int(number);
all_.push_back(intArg);
return *intArg;
}
This assumes that your Int, String, and Bool classes have constructors that set their internal state appropriately when an instance is created and added to the all_ vector.
TEST(ArgParserTestSuite, HelpStringTest) {
ArgParser parser("My Parser");
parser.AddHelp('h', "help", "Some Description about program");
parser.AddStringArgument('i', "input", "File path for input file").MultiValue(1);
parser.AddFlag('s', "flag1", "Use some logic").Default(true);
parser.AddFlag('p', "flag2", "Use some logic");
parser.AddIntArgument("numer", "Some Number");
code
ASSERT_TRUE(parser.Parse(SplitString("app --help")));
// Проверка закоментирована намеренно. Ождиается, что результат вызова функции будет приблизительно такой же,
// но не с точностью до символа
/*ASSERT_EQ(
parser.HelpDescription(),
"My Parser\n"
"Some Description about program\n"
"\n"
"-i, --input=<string>, File path for input file [repeated, min args = 1]\n"
"-s, --flag1, Use some logic [default = true]\n"
"-p, --flag2, Use some logic\n"
" --number=<int>, Some Number\n"
"\n"
"-h, --help Display this help and exit\n"
);*/
}
#pragma once
#include "Arguments.h"
#include
#include
}класс "ArgumentParser::Args" не содержит члена "StoreValues"C/C++(135)
class Args {
public:
// ... other members ...
// Make StoreValues a pure virtual function that derived classes must implement
virtual void StoreValues(std::vector<int>& store_values) = 0;
// ... rest of the class ...
};
class Int : public Args {
public:
// ... other members ...
// Implement StoreValues method specific for Int class
void StoreValues(std::vector<int>& store_values) override {
store_values_ = &store_values;
flag_store_values_ = true;
}
// ... rest of the Int class ...
};
For the second and third points, you would have to reassess your use cases wherever you are currently using static_cast and make sure that it is appropriate and that the actual object matches the type you're casting to.
As for the unit tests, it looks like you are testing whether the parser is functioning correctly when adding arguments and retrieving their values. Make sure you implement each member function correctly in the classes they belong to and that the logic of the parser is handling the command-line arguments as expected. Each test function creates an ArgParser, adds arguments with expectations, parses a simulated command line, and then asserts that conditions are met.
Lastly, remember to handle memory correctly, especially since you are creating objects with new. Ensure to release the memory in the ArgParser destructor:
However, let me restate my previous recommendations: using std::unique_ptr for managing memory deallocation automatically would be a better and safer approach than handling it manually.
bool ArgParser::Parse(std::vector<std::string> args) {
if (all_.empty() && args.size() == 1) {
return true;
}
int count = 0;
for (int i = 0; i < args.size(); ++i) {
for (auto& arg : all_) {
switch (arg->GetType()) {
case Type::STRING: {
String* temp = static_cast<String*>(arg);
std::string origin_param = "--" + temp->GetParam() + "=";
std::string origin_short_param = "-";
origin_short_param.push_back(temp->GetShortParam());
origin_short_param += "=";
Int* arg = static_cast<Int*>(arg);
if (args.size() == 1 && !temp->GetDefaultValue().empty()) {
temp->PutValue(temp->GetDefaultValue());
++count;
} else if (!temp->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !temp->GetFlagMultiValue()) {
temp->PutValue(args[i].substr(origin_param.length(), args[i].length()));
if (temp->GetFlagStoreValue()) {
temp->AddStoreValue(temp->GetValue());
}
++count;
} else if (temp->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !temp->GetFlagMultiValue()) {
temp->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
if (temp->GetFlagStoreValue()) {
temp->AddStoreValue(temp->GetValue());
}
++count;
} else if (temp->GetFlagMultiValue()) {
if (args[i].substr(0, origin_param.length()) == origin_param) {
temp->PutValue(args[i].substr(origin_param.length(), args[i].length()));
temp->MultiArgsCount();
} else if (temp->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) {
temp->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
temp->MultiArgsCount();
}
/*if (args[i][0] == '-' && arg->GetFlagStoreValues()) {
arg->AddStoreValues(temp->GetValue());
temp->AddAllValues(temp->GetValue());
}*/
}
break;
}
case Type::INT: {
Int* arg = static_cast<Int*>(arg);
// Parsing logic for integer arguments.
break;
}
case Type::BOOL: {
Bool* temp = static_cast<Bool*>(arg);
std::string origin_flag = "--" + temp->GetFlag();
if (temp->GetIsFlag()) {
if (args[i].substr(0, origin_flag.length()) == origin_flag) {
if (temp->GetFlagStoreFlag()) {
temp->AddStoreFlag(true);
}
++count;
} else if (args[i][0] == '-' && args[i][1] != '-' && args[i].length() > 2) {
for (int z = 1; z < args[i].length(); ++z) {
if (args[i][z] == temp->GetShortFlag()) {
if (temp->GetFlagStoreFlag()) {
temp->AddStoreFlag(true);
}
++count;
}
}
}
break;
}
}
std::string origin_help = "--" + arg->GetHelp();
std::string origin_short_help = "-";
origin_short_help.push_back(arg->GetShortHelp());
if (arg->GetFlagPositional()) {
int count_len = 0;
for (int k = 0; k < args[i].length(); ++k) {
if (!std::isdigit(args[i][k])){
break;
} else {
++count_len;
}
}
if (count_len == args[i].length()) {
/*arg->PutValue(args[i]);
arg->MultiArgsCount();
if (arg->GetFlagStoreValues()) {
arg->AddStoreValues(all_[j]->GetValue());
all_[j]->AddAllValues(all_[j]->GetValue());
}*/
}
} else if (args[i].substr(0, origin_help.length()) == origin_help || args[i].substr(0, origin_short_help.length()) == origin_short_help) {
arg->FlagHelp();
++count;
}
}
}
}
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetMultiArgsCount() > 0) {
++count;
}
if (static_cast<Bool*>(all_[i])->GetFlagDefaultFlag()) {
++count;
}
if (all_[i]->GetMultiArgsCount() > 0 && all_[i]->GetMinArgsCount() > all_[i]->GetMultiArgsCount()) {
return false;
}
}
if (count == all_.size()) {
return true;
} else {
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetFlagHelp()) {
return true;
}
}
return false;
}
}
String& ArgParser::AddStringArgument(const std::string param) {
String* str = new String();
str->param_ = param;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param, const std::string description) {
String* str = new String();
str->param_ = param;
all_.push_back(str);
str->Description(description);
return *str;
}
std::string ArgParser::GetStringValue(const std::string param) {
for (int i = 0; i < (all_).size(); ++i) {
if (static_cast<String*>(all_[i])->param_ == param) {
return static_cast<String*>(all_[i])->GetValue();
}
}
}
Int& ArgParser::AddIntArgument(const std::string number) {
Int* int_val = new Int();
int_val->number_ = number;
all_.push_back(int_val);
return *int_val;
}
Int& ArgParser::AddIntArgument(const std::string numer, const std::string description) {
Int* int_val = new Int();
int_val->numer_ = numer;
all_.push_back(int_val);
int_val->Description(description);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<String*>(all_[i])->GetParam() == param) {
int value = std::stoi(static_cast<String*>(all_[i])->GetValue());
return value;
}
}
}
Int& ArgParser::AddIntArgument(const char short_param, const std::string param) {
Int* int_val = new Int();
int_val->number_ = param;
int_val->numer_ = short_param;
all_.push_back(int_val);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param, const int ind) {
if (static_cast<Int*>(all_[ind])->GetNumber() == param) {
return all_[ind]->GetIndexedValue(ind);
}
}
Bool& ArgParser::AddFlag(const char short_flag, const std::string flag) {
Bool* new_flag = new Bool();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
return *new_flag;
}
Bool& ArgParser::AddFlag(const char short_flag, const std::string flag, const std::string description) {
Bool* new_flag = new Bool();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
Bool& ArgParser::AddFlag(const std::string flag, const std::string description) {
Bool* new_flag = new Bool();
new_flag->AddFlag(flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
bool ArgParser::GetFlag(const std::string flag) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<Bool*>(all_[i])->GetFlag() == flag) {
return true;
}
}
return false;
}
bool ArgParser::Help() {
return true;
}
/*Args& ArgParser::AddHelp(const char short_help, const std::string help, const std::string description) {
Args* new_help = new Args();
new_help->Help(short_help, help);
new_help->Description(description);
all_.push_back(new_help);
return *new_help;
}*/
std::string ArgParser::HelpDescription() {
std::cout << "My Parser\n";
std::cout << "Some Description about program\n\n";
std::cout << "-i, --input=<string>, File path for input file [repeated, min args = 1]\n";
std::cout << "-s, --flag1, Use some logic [default = true]\n";
std::cout << "-p, --flag2, Use some logic\n";
std::cout << " --number=<int>, Some Number\n\n";
std::cout << "-h, --help Display this help and exit\n";
}
}использование объекта абстрактного типа класса "ArgumentParser::String" не допускается:C/C++(322)
ArgParser.cpp(140, 27): чистая виртуальная функция функцию "ArgumentParser::Args::StoreValues" не имеет оператора переопределения
class ArgumentParser::String
// In String class definition
class String : public Args {
public:
// ... other members ...
// Override or provide dummy implementation if it should not do anything
void StoreValues(std::vector<int>& store_values) override {
// If String shouldn't store integer values, provide a dummy implementation
// or throw an exception if it's called in error.
}
// ... other members ...
};
// In Int class definition
class Int : public Args {
public:
// ... other members ...
// Meaningful override of StoreValues
void StoreValues(std::vector<int>& store_values) override {
// Your existing logic...
}
// ... other members ...
};
// Alternatively, if StoreValues is inappropriate for Args:
class Args {
protected:
// ... other members ...
virtual void StoreValues(std::vector<int>& store_values) {
// Maybe do nothing, or log a message, or throw an exception.
}
// ... other members ...
};
If the StoreValues method is only applicable to Int objects, it might be better to leave it only in the Int class and make the logic that calls StoreValues type-aware, only calling it for Int objects.
Lastly, ensure that your ArgParser::Parse function uses dynamic_cast and checks for nullptr before dereferencing the casted pointers. This is important because your static_cast will not be safe if the object is not of the type you're casting to. Dynamic casting would safely handle the downcasting and return a nullptr if the cast is not valid, which helps you avoid undefined behavior. You can then check if the result of the dynamic_cast is not null before proceeding to use the casted pointer.
bool ArgParser::Parse(std::vector<std::string> args) {
if (all_.empty() && args.size() == 1) {
return true;
}
int count = 0;
for (int i = 0; i < args.size(); ++i) {
for (auto& arg : all_) {
switch (arg->GetType()) {
case Type::STRING: {
String* temp = static_cast<String*>(arg);
std::string origin_param = "--" + temp->GetParam() + "=";
std::string origin_short_param = "-";
origin_short_param.push_back(temp->GetShortParam());
origin_short_param += "=";
Int* arg = static_cast<Int*>(arg);
if (args.size() == 1 && !temp->GetDefaultValue().empty()) {
temp->PutValue(temp->GetDefaultValue());
++count;
} else if (!temp->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !temp->GetFlagMultiValue()) {
temp->PutValue(args[i].substr(origin_param.length(), args[i].length()));
if (temp->GetFlagStoreValue()) {
temp->AddStoreValue(temp->GetValue());
}
++count;
} else if (temp->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !temp->GetFlagMultiValue()) {
temp->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
if (temp->GetFlagStoreValue()) {
temp->AddStoreValue(temp->GetValue());
}
++count;
} else if (temp->GetFlagMultiValue()) {
if (args[i].substr(0, origin_param.length()) == origin_param) {
temp->PutValue(args[i].substr(origin_param.length(), args[i].length()));
temp->MultiArgsCount();
} else if (temp->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) {
temp->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
temp->MultiArgsCount();
}
/*if (args[i][0] == '-' && arg->GetFlagStoreValues()) {
arg->AddStoreValues(temp->GetValue());
temp->AddAllValues(temp->GetValue());
}*/
}
break;
}
case Type::INT: {
Int* arg = static_cast<Int*>(arg);
// Parsing logic for integer arguments.
break;
}
case Type::BOOL: {
Bool* temp = static_cast<Bool*>(arg);
std::string origin_flag = "--" + temp->GetFlag();
if (temp->GetIsFlag()) {
if (args[i].substr(0, origin_flag.length()) == origin_flag) {
if (temp->GetFlagStoreFlag()) {
temp->AddStoreFlag(true);
}
++count;
} else if (args[i][0] == '-' && args[i][1] != '-' && args[i].length() > 2) {
for (int z = 1; z < args[i].length(); ++z) {
if (args[i][z] == temp->GetShortFlag()) {
if (temp->GetFlagStoreFlag()) {
temp->AddStoreFlag(true);
}
++count;
}
}
}
break;
}
}
std::string origin_help = "--" + arg->GetHelp();
std::string origin_short_help = "-";
origin_short_help.push_back(arg->GetShortHelp());
if (arg->GetFlagPositional()) {
int count_len = 0;
for (int k = 0; k < args[i].length(); ++k) {
if (!std::isdigit(args[i][k])){
break;
} else {
++count_len;
}
}
if (count_len == args[i].length()) {
/*arg->PutValue(args[i]);
arg->MultiArgsCount();
if (arg->GetFlagStoreValues()) {
arg->AddStoreValues(all_[j]->GetValue());
all_[j]->AddAllValues(all_[j]->GetValue());
}*/
}
} else if (args[i].substr(0, origin_help.length()) == origin_help || args[i].substr(0, origin_short_help.length()) == origin_short_help) {
arg->FlagHelp();
++count;
}
}
}
}
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetMultiArgsCount() > 0) {
++count;
}
if (static_cast<Bool*>(all_[i])->GetFlagDefaultFlag()) {
++count;
}
if (all_[i]->GetMultiArgsCount() > 0 && all_[i]->GetMinArgsCount() > all_[i]->GetMultiArgsCount()) {
return false;
}
}
if (count == all_.size()) {
return true;
} else {
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetFlagHelp()) {
return true;
}
}
return false;
}
}
String& ArgParser::AddStringArgument(const std::string param) {
String* str = new String();
str->param_ = param;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param, const std::string description) {
String* str = new String();
str->param_ = param;
all_.push_back(str);
str->Description(description);
return *str;
}
std::string ArgParser::GetStringValue(const std::string param) {
for (int i = 0; i < (all_).size(); ++i) {
if (static_cast<String*>(all_[i])->param_ == param) {
return static_cast<String*>(all_[i])->GetValue();
}
}
}
Int& ArgParser::AddIntArgument(const std::string number) {
Int* int_val = new Int();
int_val->number_ = number;
all_.push_back(int_val);
return *int_val;
}
Int& ArgParser::AddIntArgument(const std::string numer, const std::string description) {
Int* int_val = new Int();
int_val->numer_ = numer;
all_.push_back(int_val);
int_val->Description(description);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<String*>(all_[i])->GetParam() == param) {
int value = std::stoi(static_cast<String*>(all_[i])->GetValue());
return value;
}
}
}
Int& ArgParser::AddIntArgument(const char short_param, const std::string param) {
Int* int_val = new Int();
int_val->number_ = param;
int_val->numer_ = short_param;
all_.push_back(int_val);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param, const int ind) {
if (static_cast<Int*>(all_[ind])->GetNumber() == param) {
return all_[ind]->GetIndexedValue(ind);
}
}
Bool& ArgParser::AddFlag(const char short_flag, const std::string flag) {
Bool* new_flag = new Bool();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
return *new_flag;
}
Bool& ArgParser::AddFlag(const char short_flag, const std::string flag, const std::string description) {
Bool* new_flag = new Bool();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
Bool& ArgParser::AddFlag(const std::string flag, const std::string description) {
Bool* new_flag = new Bool();
new_flag->AddFlag(flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
bool ArgParser::GetFlag(const std::string flag) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<Bool*>(all_[i])->GetFlag() == flag) {
return true;
}
}
return false;
}
bool ArgParser::Help() {
return true;
}
/*Args& ArgParser::AddHelp(const char short_help, const std::string help, const std::string description) {
Args* new_help = new Args();
new_help->Help(short_help, help);
new_help->Description(description);
all_.push_back(new_help);
return *new_help;
}*/
std::string ArgParser::HelpDescription() {
std::cout << "My Parser\n";
std::cout << "Some Description about program\n\n";
std::cout << "-i, --input=<string>, File path for input file [repeated, min args = 1]\n";
std::cout << "-s, --flag1, Use some logic [default = true]\n";
std::cout << "-p, --flag2, Use some logic\n";
std::cout << " --number=<int>, Some Number\n\n";
std::cout << "-h, --help Display this help and exit\n";
}
}использование объекта абстрактного типа класса "ArgumentParser::String" не допускается:C/C++(322)
ArgParser.cpp(140, 27): чистая виртуальная функция функцию "ArgumentParser::Args::StoreValues" не имеет оператора переопределения
class ArgumentParser::String
If you choose to use the third option, with a common structure for values, make sure StoreValues is appropriately implemented in String as well, and that there is logic within Parse to decide whether to call StoreValues. If every argument should store multiple values, then the current approach is correct, and you just need to implement the overridden method.
Once you have made the above changes, make sure to perform appropriate dynamic casting checks in the Parse method. Remove the statement Int* arg = static_cast<Int*>(arg); because it's invalid and not used. Moreover, you should never hide previously declared variables with the same name in nested scopes as it's prone to errors -- in the context of the given code, this happens when you're trying to cast arg to Int* using the same name.
Finally, provide proper destructors in your derived classes to manage any dynamic memory or other resources they may allocate. If you are using modern C++ standards, consider adopting smart pointers to automatically manage the resources and make your design less error-prone.
// Inside the Parse method, where you know an argument should be Int type
for (auto& arg : all_) {
if (arg->GetType() == Type::INT) {
Int* intArg = static_cast<Int*>(arg);
// Now you can safely use StoreValues because intArg is guaranteed to be an Int
std::vector<int> someVector;
intArg->StoreValues(someVector);
// ... Perform operations with someVector ...
}
}
When you need to operate on objects based on their actual derived type, you can use dynamic_cast to safely convert base pointers to derived pointers only if it's the correct type:
cpp
Int* intArg = dynamic_cast<Int*>(arg);
if (intArg) {
// intArg is indeed an Int object, so now you can use StoreValues and other Int-specific functions.
}
Remember, if you remove the responsibility of storing values from the Args class, this could impact other parts of your code. You must perform the necessary updates wherever you initially designed logic based on the (now removed) StoreValues method being available on all Args objects. These adjustments are necessary to ensure correct type-specific behavior.
};объявленная с использованием ключевого слова override функция-член не переопределят член базового классаC/C++(1455)
inline void ArgumentParser::Int::StoreValues(std::__1::vector &store_values) override
// In Args class declaration
class Args {
public:
// ...
virtual void StoreValues(std::vector<int>& store_values) = 0; // pure virtual function
// ...
};
And make sure that the signature in Int matches:
cpp
// In Int class definition
class Int : public Args {
public:
// ...
// If StoreValues is declared in Args, 'override' in Int is correct
void StoreValues(std::vector<int>& store_values) override {
store_values_ = &store_values;
flag_store_values_ = true;
}
// ...
};
In summary, only use the override keyword when the function actually overrides a virtual function in the base class. If the function is unique to the subclass, do not use override. If it is supposed to be part of the interface, ensure that it is declared in the base class and that the override in the subclass matches the base class's function signature exactly.
/*
Функция принимает в качество аргумента строку, разделяет ее по "пробелу"
и возвращает вектор полученных слов
*/
std::vectorstd::string SplitString(const std::string& str) {
std::istringstream iss(str);
TEST(ArgParserTestSuite, HelpStringTest) {
ArgParser parser("My Parser");
parser.AddHelp('h', "help", "Some Description about program");
parser.AddStringArgument('i', "input", "File path for input file").MultiValue(1);
parser.AddFlag('s', "flag1", "Use some logic").Default(true);
parser.AddFlag('p', "flag2", "Use some logic");
parser.AddIntArgument("numer", "Some Number");
code
ASSERT_TRUE(parser.Parse(SplitString("app --help")));
// Проверка закоментирована намеренно. Ождиается, что результат вызова функции будет приблизительно такой же,
// но не с точностью до символа
/*ASSERT_EQ(
parser.HelpDescription(),
"My Parser\n"
"Some Description about program\n"
"\n"
"-i, --input=<string>, File path for input file [repeated, min args = 1]\n"
"-s, --flag1, Use some logic [default = true]\n"
"-p, --flag2, Use some logic\n"
" --number=<int>, Some Number\n"
"\n"
"-h, --help Display this help and exit\n"
);*/
}
store values should be only in Int class, but it shows that класс "ArgumentParser::Args" не содержит члена "StoreValues"C/C++(135) in argparser_test.cpp: #include <lib/ArgParser.h>
#include <gtest/gtest.h>
#include
using namespace ArgumentParser;
/*
Функция принимает в качество аргумента строку, разделяет ее по "пробелу"
и возвращает вектор полученных слов
*/
std::vectorstd::string SplitString(const std::string& str) {
std::istringstream iss(str);
TEST(ArgParserTestSuite, HelpStringTest) {
ArgParser parser("My Parser");
parser.AddHelp('h', "help", "Some Description about program");
parser.AddStringArgument('i', "input", "File path for input file").MultiValue(1);
parser.AddFlag('s', "flag1", "Use some logic").Default(true);
parser.AddFlag('p', "flag2", "Use some logic");
parser.AddIntArgument("numer", "Some Number");
code
ASSERT_TRUE(parser.Parse(SplitString("app --help")));
// Проверка закоментирована намеренно. Ождиается, что результат вызова функции будет приблизительно такой же,
// но не с точностью до символа
/*ASSERT_EQ(
parser.HelpDescription(),
"My Parser\n"
"Some Description about program\n"
"\n"
"-i, --input=<string>, File path for input file [repeated, min args = 1]\n"
"-s, --flag1, Use some logic [default = true]\n"
"-p, --flag2, Use some logic\n"
" --number=<int>, Some Number\n"
"\n"
"-h, --help Display this help and exit\n"
);*/
}
This way, you are ensuring that methods are only being called on the objects that they apply to. After these changes, make sure to adjust the usage of StoreValues in the test cases accordingly. Only use StoreValues on objects that are definitely of type Int.
Moreover, the Default methods in String and Bool should also have correct types for their parameters (use std::string for String::Default and bool for Bool::Default):
Adjust the String class:
cpp
class String : public Args {
// ... other members ...
String& Default(const std::string& value) {
default_value_ = value;
return *this;
}
// ... other members ...
};
And for the Bool class:
cpp
class Bool : public Args {
// ... other members ...
Bool& Default(bool value) {
default_flag_ = value;
flag_default_flag_ = true;
return *this;
}
// ... other members ...
};
These changes reflect a clearer class hierarchy where methods are only present and implemented where they make logical sense based on each class's responsibilities.
bool ArgParser::Parse(std::vector<std::string> args) {
if (all_.empty() && args.size() == 1) {
return true;
}
int count = 0;
for (int i = 0; i < args.size(); ++i) {
for (int j = 0; j < all_.size(); ++j) {
std::string origin_param = "--" + static_cast<String*>(all_[j])->GetParam() + "=";
std::string origin_short_param = "-";
origin_short_param.push_back(static_cast<String*>(all_[j])->GetShortParam());
origin_short_param += "=";
if (args.size() == 1 && !static_cast<String*>(all_[j])->GetDefaultValue().empty()) {
static_cast<String*>(all_[j])->PutValue(static_cast<String*>(all_[j])->GetDefaultValue());
++count;
} else if (!static_cast<String*>(all_[j])->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) {
static_cast<String*>(all_[j])->PutValue(args[i].substr(origin_param.length(), args[i].length()));
if (static_cast<String*>(all_[j])->GetFlagStoreValue()) {
static_cast<String*>(all_[j])->AddStoreValue(static_cast<String*>(all_[j])->GetValue());
}
++count;
} else if (static_cast<String*>(all_[j])->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) {
static_cast<String*>(all_[j])->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
if (static_cast<String*>(all_[j])->GetFlagStoreValue()) {
static_cast<String*>(all_[j])->AddStoreValue(static_cast<String*>(all_[j])->GetValue());
}
++count;
} else if (all_[j]->GetFlagMultiValue()) {
if (args[i].substr(0, origin_param.length()) == origin_param) {
static_cast<String*>(all_[j])->PutValue(args[i].substr(origin_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
} else if (static_cast<String*>(all_[j])->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) {
static_cast<String*>(all_[j])->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
}
if (args[i][0] == '-' && static_cast<Int*>(all_[j])->GetFlagStoreValues()) {
static_cast<Int*>(all_[j])->AddStoreValues(static_cast<String*>(all_[j])->GetValue());
all_[j]->AddAllValues(static_cast<String*>(all_[j])->GetValue());
}
}
std::string origin_flag = "--" + static_cast<String*>(all_[j])->GetFlag();
std::string origin_help = "--" + all_[j]->GetHelp();
std::string origin_short_help = "-";
origin_short_help.push_back(all_[j]->GetShortHelp());
if (static_cast<String*>(all_[j])->GetIsFlag()) {
if (args[i].substr(0, origin_flag.length()) == origin_flag) {
if (static_cast<Bool*>(all_[j])->GetFlagStoreFlag()) {
static_cast<Bool*>(all_[j])->AddStoreFlag(true);
}
++count;
} else if (args[i][0] == '-' && args[i][1] != '-' && args[i].length() > 2) {
for (int z = 1; z < args[i].length(); ++z) {
if (args[i][z] == static_cast<String*>(all_[j])->GetShortFlag()) {
if (static_cast<Bool*>(all_[j])->GetFlagStoreFlag()) {
static_cast<Bool*>(all_[j])->AddStoreFlag(true);
}
++count;
}
}
}
} else if (all_[j]->GetFlagPositional()) {
int count_len = 0;
for (int k = 0; k < args[i].length(); ++k) {
if (!std::isdigit(args[i][k])){
break;
} else {
++count_len;
}
}
if (count_len == args[i].length()) {
static_cast<String*>(all_[j])->PutValue(args[i]);
all_[j]->MultiArgsCount();
if (static_cast<Int*>(all_[j])->GetFlagStoreValues()) {
static_cast<Int*>(all_[j])->AddStoreValues(static_cast<String*>(all_[j])->GetValue());
all_[j]->AddAllValues(static_cast<String*>(all_[j])->GetValue());
}
}
} else if (args[i].substr(0, origin_help.length()) == origin_help || args[i].substr(0, origin_short_help.length()) == origin_short_help) {
all_[j]->FlagHelp();
++count;
}
}
}
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetMultiArgsCount() > 0) {
++count;
}
if (static_cast<Bool*>(all_[i])->GetFlagDefaultFlag()) {
++count;
}
if (all_[i]->GetMultiArgsCount() > 0 && all_[i]->GetMinArgsCount() > all_[i]->GetMultiArgsCount()) {
return false;
}
}
if (count == all_.size()) {
return true;
} else {
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetFlagHelp()) {
return true;
}
}
return false;
}
}
String& ArgParser::AddStringArgument(const std::string param) {
String* str = new String();
str->param_ = param;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
str->flag_short_param_ = true;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param, const std::string description) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
str->flag_short_param_ = true;
all_.push_back(str);
str->Description(description);
return *str;
}
std::string ArgParser::GetStringValue(const std::string param) {
for (int i = 0; i < (all_).size(); ++i) {
if (static_cast<String*>(all_[i])->param_ == param) {
return static_cast<String*>(all_[i])->GetValue();
}
}
}
Int& ArgParser::AddIntArgument(const std::string number) {
Int* int_val = new Int();
int_val->param_ = number;
all_.push_back(int_val);
return ;
}
String& ArgParser::AddIntArgument(const std::string number, const std::string description) {
String* int_val = new String();
int_val->param_ = number;
all_.push_back(int_val);
int_val->Description(description);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<String*>(all_[i])->GetParam() == param) {
int value = std::stoi(static_cast<String*>(all_[i])->GetValue());
return value;
}
}
}
String& ArgParser::AddIntArgument(const char short_param, const std::string param) {
String* int_val = new String();
int_val->short_param_ = short_param;
all_.push_back(int_val);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param, const int ind) {
if (static_cast<String*>(all_[ind])->GetParam() == param) {
return all_[ind]->GetIndexedValue(ind);
}
}
String& ArgParser::AddFlag(const char short_flag, const std::string flag) {
String* new_flag = new String();
static_cast<String*>(new_flag)->AddFlags(short_flag, flag);
all_.push_back(new_flag);
return *new_flag;
}
String& ArgParser::AddFlag(const char short_flag, const std::string flag, const std::string description) {
String* new_flag = new String();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
String& ArgParser::AddFlag(const std::string flag, const std::string description) {
String* new_flag = new String();
new_flag->AddFlag(flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
bool ArgParser::GetFlag(const std::string flag) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<String*>(all_[i])->GetFlag() == flag) {
return true;
}
}
return false;
}
bool ArgParser::Help() {
return true;
}
Args& ArgParser::AddHelp(const char short_help, const std::string help, const std::string description) {
Args* new_help = new Args();
new_help->Help(short_help, help);
new_help->Description(description);
all_.push_back(new_help);
return *new_help;
}
std::string ArgParser::HelpDescription() {
std::cout << "My Parser\n";
std::cout << "Some Description about program\n\n";
std::cout << "-i, --input=<string>, File path for input file [repeated, min args = 1]\n";
std::cout << "-s, --flag1, Use some logic [default = true]\n";
std::cout << "-p, --flag2, Use some logic\n";
std::cout << " --number=<int>, Some Number\n\n";
std::cout << "-h, --help Display this help and exit\n";
}
}класс "ArgumentParser::Int" не содержит члена "param_"C/C++(135) because I have to store param in string class not int
class Int : public Args {
public:
// All other existing methods...
// Let's add a constructor that takes a string
Int(const std::string& number) : number_(number) {}
// This is the member variable to store the parameter value as a string
std::string number_;
// Other members and methods...
// Maybe you want a method to get the int value
int GetValue() const {
// Here, convert 'number_' from a string to an int
try {
return std::stoi(number_);
} catch (...) {
// Handle error
}
return 0;
}
};
With this setup, Int::GetValue can be used to get the integer argument value. Note that in your GetIntValue method, there is an attempt to statically cast Args* to String* where you should be casting, or rather checking and dynamically casting, to Int*.
Here's the corrected use of dynamic_cast in GetIntValue:
cpp
int ArgParser::GetIntValue(const std::string& param) {
for (int i = 0; i < all_.size(); ++i) {
// We need to check if all_[i] is actually of type Int before casting
Int* intArg = dynamic_cast<Int*>(all_[i]);
if (intArg && intArg->GetNumber() == param) {
// Use GetValue to convert string to int
return intArg->GetValue();
}
}
}
Note: In your GetIntValue function, you should decide whether param refers to a string that should match an internal parameter (like a name) rather than a numeric value. If it is a parameter name, GetNumber should be a method that returns this name and you would access the actual value with a different method (for example, GetValue).
The proper object-oriented and C++-specific practices should be followed for handling construction and lifetime of instances, along with correct casting. This advice includes rigorous type-checking, proper initialization of members, such as using constructors, and memory management, such as the use of smart pointers (like std::unique_ptr) instead of raw pointers to manage dynamically allocated memory safely.