如何在C++ 11中实现类型化字符串?

aby*_*s.7 6 c++ syntactic-sugar c++11

在我的项目中,在同一范围内有许多具有不同含义的字符串,例如:

std::string function_name = "name";
std::string hash = "0x123456";
std::string flag = "--configure";
Run Code Online (Sandbox Code Playgroud)

我想通过它们的含义来区分不同的字符串,以便与函数重载一起使用:

void Process(const std::string& string_type1);
void Process(const std::string& string_type2);
Run Code Online (Sandbox Code Playgroud)

显然,我必须使用不同的类型:

void Process(const StringType1& string);
void Process(const StringType2& string);
Run Code Online (Sandbox Code Playgroud)

但是如何以优雅的方式实现这些类型呢?我所能得到的就是:

class StringType1 {
  std::string str_;
 public:
  explicit StringType1(const std::string& str) : str_(str) {}
  std::string& toString() { return str_; }
};

// Same thing with StringType2, etc.
Run Code Online (Sandbox Code Playgroud)

你能建议更方便吗?


重命名函数没有意义,因为主要目标是不要错误地传递一种字符串类型而不是另一种字符串:

void ProcessType1(const std::string str);
void ProcessType2(const std::string str);

std::string str1, str2, str3;

// What should I pass where?..
Run Code Online (Sandbox Code Playgroud)

o11*_*11c 6

您可能想要一个带有tag参数的模板:

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

struct FunctionName;
MyString<FunctionName> function_name;
Run Code Online (Sandbox Code Playgroud)


Ore*_*hon 1

您的目标设计是继承,如此处的其他答案(*)所示。但你不应该继承 std::string。您可以找到许多关于它的讨论,例如:Inheriting and overrideing functions of a std::string?

它给你留下了你的第一个想法,实际实现了构图的概念。

(*) 我会在该答案中发表评论,而不是打开新答案,但我还不能发表评论。