How can I speed up this inline template function?

// Function: from_value
// Purpose: Convert a number to a RString
// Inputs:   <Template Type>   Argument1: Number Arg2: Digits-to-show
// Usage:      Double to RString
//                  AString = from_value<double>(SomeDouble, 5)
template<typename TheType>
inline RString from_value(TheType Val, short Precision) {
  stringstream SS;
  RString Str;

  //Convert the value to a string via stringstream
  // setprecision() sets the # of digits to display
  SS << setprecision(Precision) << Val;

  //Convert the string stream to an RString and return it
  SS >> Str;
  return Str;

Just to repeat my comments above, this is designed to be a way to simplify the process of converting a number to a string.
The string here is said to be an RString ... but an RString in my case is a std::basic_string with a memory pool allocator.

SomeString = from_value<double>(SomeDouble, 5);

Is there a way for me to cut down on any CPU cycles or copies/allocations?

I'm tempted to create a static stringstream & RString in the header which contains this function so that that memory can be reused.

Thanks in advance for your time.
Who is Participating?
e_tadeuConnect With a Mentor Commented:
You don't need to specify template types for templated functions when the types are implicitly passed :)

Again: if you want to really speed up it, use sprintf, otherwise you will need to do your own implementation of stringstream/string (a long way, a lot of job, i don't see it as necessary)
oxygen_728Author Commented:
I'd also be interested to know why this function works without specifying a type

example:   SomeString = from_value(SomeDouble, 5);

Seems like the first argument of the function should have some problems when a type isn't specified - obviously I'm wrong though!
oxygen_728Author Commented:
I'm a bit curious what you mean when you say "the types are implicitly passed"

Could you elaborate a little please?

Thanks e_tadeu
For example:

template <class T>
T square(T x) {
  return x * x;

int a = 5;
double b = 3.0;

int a2 = square(a); // will call square<int>(a)
int b2 = square(b); // will call square<double(b)
int c2 = square('c'); // will call square<char>(c)

Because the compiler knows the right types of a, b, and 'c' (int, double and char), it can call the corresponding template function, passing the type "implicitly" (hidden) :)

oxygen_728Author Commented:
Ahhh... so it's mostly to specify if it's a template class or something.

cool =)

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.