In my project there are a lot of strings with different meanings at the same scope, like:
std::string function_name = "name";
std::string hash = "0x123456";
std::string flag = "--configure";
I want to distinguish different strings by their meaning, to use with function overloads:
void Process(const std::string& string_type1);
void Process(const std::string& string_type2);
Obviously, I have to use different types:
void Process(const StringType1& string);
void Process(const StringType2& string);
But how to implement those types in an elegant manner? All I can come with is this:
class StringType1 {
std::string str_;
public:
explicit StringType1(const std::string& str) : str_(str) {}
std::string& toString() { return str_; }
};
// Same thing with StringType2, etc.
Can you advise more convenient way?
There is no point in renaming functions since the main goal is to not mistakenly pass one string type instead of another:
void ProcessType1(const std::string str);
void ProcessType2(const std::string str);
std::string str1, str2, str3;
// What should I pass where?..
In C programming, a string is a sequence of characters terminated with a null character \0 . For example: char c[] = "c string"; When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default.
Overview. The C language does not have a specific "String" data type, the way some other languages such as C++ and Java do. Instead C stores strings of characters as arrays of chars, terminated by a null byte.
In order to use the string data type, the C++ string header <string> must be included at the top of the program. Also, you'll need to include using namespace std; to make the short name string visible instead of requiring the cumbersome std::string.
You probably want a template with a tag parameter:
template<class Tag>
struct MyString
{
std::string data;
};
struct FunctionName;
MyString<FunctionName> function_name;
Simple approach:
struct flag {
string value;
};
struct name {
string value;
};
You could improve this with implicit conversions to strings or other memberfunctions, too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With