Jump to content

[SOLVED] C++ static templates


AggrorJorn
 Share

Recommended Posts

Hi everyone,

 

One of things that I can't seem to get working is using a static method. I have written a simple Int to string function that I want to be able to call everywhere in the program. I am using a template to let you convert anything to a string.

#include <sstream>
class Convert
{
template <class T>
static inline std::string ToString (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
}

 

So my question is: How would I achieve this and what are alternatives to using static?

Link to comment
Share on other sites

I use a base Object class called "Object" and have a virtual function on the object class called "ToString". Then each derived class can have its own variation.

My job is to make tools you love, with the features you want, and performance you can't live without.

Link to comment
Share on other sites

Hey Aggror!

 

1. You forget a closing bracket at the end.

2. All Methods and Variables declared without a specific access space are default in private (opposite to struct where all entires automatically public)

 

So your working class look like this:

 

#include <sstream>
class Convert
{
public:
template <class T>
static inline std::string ToString (const T& t)
{
 std::stringstream ss;
 ss << t;
 return ss.str();
}
};

 

 

Simple Test code from me:

#include <windows.h>
#include <iostream>
#include <stdio.h>
#include "convert.h"
int main(int argc, char** argv)
{
int a = 12345;
float b = 54321.0f;
std::cout << Convert::ToString<int>(a) << std::endl;
std::cout << Convert::ToString<float>(B) << std::endl;
system("pause");
return 0;
}

 

Cheers :)

Link to comment
Share on other sites

Yepp. Smashthewindow is right. Just make a namespace Convert and place your conversion functions there

 

 

#include <sstream>

namespace Convert

{

template <class T>

inline std::string ToString (const T& t)

{

std::stringstream ss;

ss << t;

return ss.str();

}

}

 

 

#include <iostream>

#include <stdio.h>

#include "convert.h"

int main(int argc, char** argv)

{

int a = 12345;

float b = 54321.0f;

std::cout << Convert::ToString<int>(a) << std::endl;

std::cout << Convert::ToString<float>(B) << std::endl;

system("pause");

return 0;

}

Roland Strålberg
Website: https://rstralberg.com

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...