加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:21:27 所属栏目:百科 来源:网络整理
导读:在我的项目中,在同一范围内有许多具有不同含义的字符串,例如: std::string function_name = "name";std::string hash = "0x123456";std::string flag = "--configure"; 我想通过它们的含义来区分不同的字符串,以便与函数重载一起使用: void Process(const
在我的项目中,在同一范围内有许多具有不同含义的字符串,例如:
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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读