c++ - Faster constant string appending without macro -


so when combining strings, oftentimes there constant components, example:

std::string s; s += initial_string; s += "const string"; s += terminating_string; 

that's demonstration, string operations can quite bit more complex , in-depth. so, when doing const part, implementation ends "not knowing" length , strlen() on it. waste, length known @ compile time. i've tested replacing const string part quite bit faster (substantially more in x64 whatever reason):

s.append("const string",12); 

it's annoying, time-consuming, , error-prone count characters, little better:

s.append("const string",sizeof("const string")-1); 

that's still error prone (i.e. change first part forget change second part) macro can this:

#define strnsizeof(s) s,sizeof(s)-1 s.append(strnsizeof("const string")); 

question 1: have better/cleaner solution this?

i've got extended string class use << operator concatenating strings , various other object types. similar issue here, nice , clean (to me):

s << initial_string << "const string" << terminating_string; 

when have operator own object type (of length component) append operation fast , easy, when gets const char * here again, don't length though it's constant @ compile time. can speed creating little structure takes const char * , length along lines of:

s << initial_string     << mystr::constbuf(strnsizeof("const string"))     << terminating_string; 

boy getting ugly. macro out too, e.g.:

#define mystrconst(s) mystr::constbuf(s,sizeof(s)-1) s << initial_string     << mystrconst("const string")     << terminating_string; 

better not great.

question 2: got better/cleaner solution encapsulating constant string?

comments question resulted in template following:

template<size_t sz> std::string& operator<<( std::string &s, const char(&arr)[sz] ) {     s.append( arr, sz-1 );     return s; } 

so instead of s += "const string" template utilized when doing:

s << "const string" 

additionally, able update extended string class such following utilizes template constant size well:

s << initial_string << "const string" << terminating_string; 

edit: not work expected:

typedef struct { char buffer[32]; } st; st st = { "1234" }; s << st.buffer;  // results in s size 31! 

this can solved via non-const template, e.g.:

template<size_t sz> std::string& operator<<( std::string &s, char(&arr)[sz] ) {     s.append( arr ); // note not using sz here strlen happens     return s; } 

so now:

s << st.buffer;  // results in s size 4 

except:

const st cst = &st; s << cst.buffer;  // results in s size 31 again... 

same issue when buffer in class, you'd expect.


Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

jquery - How would i go about shortening this code? And to cancel the previous click on click of new section? -