In C ++ 11, this was done too simply. Use std::to_string() as:
std::string query = "select * from bla limit " + std::to_string(max_limit);
Done!
OLD SOLUTION, for those still using C ++ 03.
Use stringbuilder and create std::string on the fly as:
std::string query = stringbuilder() << "select * from bla limit " << max_limit;
where stringbuilder is implemented as:
struct stringbuilder { std::stringstream ss; template<typename T> stringbuilder & operator << (const T &data) { ss << data; return *this; } operator std::string() { return ss.str(); } };
You can use stringbuilder many ways, for example:
std::string g(int m, int n) { //create string on the fly and returns it if ( m < n ) return stringbuilder() << m << " is less than " << n ; return stringbuilder() << n << " is less than " << m ; } void f(const std::string & s ); //call f while creating string on the fly and passing it to the function f(stringbuilder() << '{' << pc << '}' ); //passed as std::string //this is my most favorite line std::string s = stringbuilder() << 23 << " is greater than " << 5 ;
Watch the demo at ideone: http://ideone.com/J995r
And look at my blog on this: Create a line "on the fly" in only one line
Nawaz source share