Navaneeth K N
Navaneeth K N

Reputation: 15501

Making a method template - C++

Below code is used to get a std::string representation from ASCII code.

string Helpers::GetStringFromASCII(const int asciiCode) const
{
    return string(1,char(asciiCode));
}

It works well. But in my application, I know the ASCII codes at compile time. So I will be calling it like

string str =  GetStringFromASCII(175) // I know 175 at compile time

Question

Is there any way to make the GetStringFromASCII method a template so that the processing happens at compile time and I can avoid calling the function each time at runtime.

Any thoughts?

Upvotes: 0

Views: 1222

Answers (4)

Mr Fooz
Mr Fooz

Reputation: 111856

How about something like this:

#include <iostream>
#include <string>

using namespace std;

template <int asciiCode>
inline string const &getStringFromASCII()
{
  static string s(1,char(asciiCode));
  return s;
}

int main(int, char const**) {
  cout << getStringFromASCII<65>() << endl;
}

EDIT: returns a ref now

Upvotes: 0

Rob K
Rob K

Reputation: 8926

Why are you even bothering with a helper function?

string s( 1, char(175) ); 

That's all you need and it's the quickest you're going to get.

Upvotes: 0

G S
G S

Reputation: 36828

This kind of template meta programming works well when you're dealing with primitive data types like ints and floats. If you necessarily need a string object, you can't avoid calling the std::string constructor and there's no way that call can happen at compile time. Also, I don't think you can drag the cast to char to compile time either, which, in all, means that templates cannot help you here.

Upvotes: 4

jturcotte
jturcotte

Reputation: 1273

Instead of feeding an int constant to a string conversion function, use a string constant directly:

string str("\xAF"); // 0xAF = 175

By the way, except for heavy performance needs in a loop, trading code readability for some CPU cycles is rarely money effective overall.

Upvotes: 3

Related Questions