Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement typed strings in C++11?

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?..
like image 452
abyss.7 Avatar asked Nov 01 '14 08:11

abyss.7


People also ask

How are strings implemented in C?

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.

Is there a type string in C?

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.

How can we use string data type in a C++ program?

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.


2 Answers

You probably want a template with a tag parameter:

template<class Tag>
struct MyString
{
    std::string data;
};

struct FunctionName;
MyString<FunctionName> function_name;
like image 144
o11c Avatar answered Sep 28 '22 18:09

o11c


Simple approach:

struct flag {
    string value;
};
struct name {
    string value;
};

You could improve this with implicit conversions to strings or other memberfunctions, too.

like image 27
Ulrich Eckhardt Avatar answered Sep 28 '22 18:09

Ulrich Eckhardt