简体   繁体   中英

C++ helper function

I have lots of code like this:

otherString1 = myString1.replace("a", "b").replace("c", "d").replace("e", "f");
otherString2 = myString2.replace("a", "b").replace("c", "d").replace("e", "f");
otherString3 = myString3.replace("a", "b").replace("c", "d").replace("e", "f");

I would like to not repeat those replace methods again and again. What is the right approach to re-factoring of such code? I'm new to C++...

I thought I could do:

#define REPLACE .replace("a", "b").replace("c", "d").replace("e", "f")
otherString1 = myString1#REPLACE;

but this does not work.

I obviously cannot monkey-patch the string class to add myReplace() ...

What to do? And should I put the replacement code into header or the sourse file? What about those static , inline , const things? Should I create a whole helper class and a helper method or should I create just a function somewhere? What about something like:

[helper.hpp]
static inline const myReplace(const StringClass s);

[helper.cpp]
static inline const myReplace(const StringClass s) {
    return s.replace("a", "b").replace("c", "d").replace("e", "f");
}

[somefile.cpp]
include "helper.hpp"
otherString3 = myReplace(myString3);

IMO, you are overthinking it. Just create a function that takes a string (by const reference) and returns the modified string. Declare it in a header and define in the corresponding .cpp file.

Job done.

[helper.hpp]
std::string myReplace(const std::string& s);

[helper.cpp]
std::string myReplace(const std::string& s) {
   ...
}

[somefile.cpp]
#include "helper.hpp"
otherString3 = myReplace(myString3);

I just want to point out that your macro would have worked, you just used it incorrectly. However, this is not the right way to solve this problem , just wanted to point it out. Here's the correct usage:

#define REPLACE .replace("a", "b").replace("c", "d").replace("e", "f")
otherString1 = myString1 REPLACE;

Or maybe better (if using macros can ever be better):

#define REPLACE(str) str.replace("a", "b").replace("c", "d").replace("e", "f")
otherString1 = REPLACE(myString1);

Remember, don't do this , but this is how macros could be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM