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

在我的项目中,在同一范围内有许多具有不同含义的字符串,例如:
std::string function_name = "name";
std::string hash = "0x123456";
std::string flag = "--configure";

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

void Process(const std::string& string_type1);
void Process(const std::string& string_type2);

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

void Process(const StringType1& string);
void Process(const StringType2& string);

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

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

// Same thing with StringType2,etc.

你能建议更方便吗?

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

void Processtype1(const std::string str);
void Processtype2(const std::string str);

std::string str1,str2,str3;

// What should I pass where?..

解决方法

您可能想要一个带有tag参数的模板:
template<class Tag>
struct MyString
{
    std::string data;
};

struct FunctionName;
MyString<FunctionName> function_name;

相关文章

对象的传值与返回说起函数,就不免要谈谈函数的参数和返回值...
从实现装饰者模式中思考C++指针和引用的选择最近在看...
关于vtordisp知多少?我相信不少人看到这篇文章,多半是来自...
那些陌生的C++关键字学过程序语言的人相信对关键字并...
命令行下的树形打印最近在处理代码分析问题时,需要将代码的...
虚函数与虚继承寻踪封装、继承、多态是面向对象语言的三大特...