is it possible to pass any var type to func?

Is it possible to make function that would accept any type of variable and then auto convert it to string?

There seems to be so many problems with variable type, for example when you try to pass char to func that expects str or if func expects unicode but you pass it ascii or if you pass it any type of number you have also problem.


Is it possible to make function that would accept any type string including number types and then conver it to right type?

I mean if I do something like

void DoThis(type value){}

Then I am not allowed to pass variable that are from other type. I wonder if there is any way to remove that requirement. and then make function autodetect type of var?

just want to know if such thing is possible.
Try this;
1
2
template <typename T>
void doThis (T value);


And take a look at : http://www.cplusplus.com/doc/tutorial/templates/
Last edited on
+1 @ mindfog.

Having said that, the C way of doing this is using a void pointer, but then how will you detect the variable type? Void pointers don't carry any useful information with them, like the size in bytes.

If you are programming Windows (and maybe other OS's ?? ), Microsoft defined the VARIANT structure which is used in COM and is "polymorphic". It has the vt member that tells you the type of value stored in the VARIANT structure.
You'll also need to use stringstreams to convert it properly. I acutally just wrote a template function to do that yesterday:

1
2
#include <sstream>
#include <string> 
1
2
3
4
5
6
7
template <typename T>
std::string ToString( const T& x )
  {
  std::ostringstream ss;
  ss << x;
  return ss.str();
  }

Keep in mind that a template function is not just one function, but a cookie-cutter design to create many functions -- one for each type T object that you pass to it. For example, the following code causes the compiler to create two ToString() functions; one that takes an int argument and one that takes a double:

1
2
string an_int   = ToString( 42 );
string a_double = ToString( 3.14159265 );

You can also be very explicit about what kind of object the argument is:

 
string a_float  = ToString <float> ( 3.14159265 );

Hope this helps.
Last edited on
thanks

ToString( 42 ); << if you dont use dot in name it's declared as int by default? and dot autom makes it float?

that's interesting.
There are rules to how the compiler assignes types to literal values. In this case, yes, you need to explicitly indicate it is a floating point number. You can do so in a number of ways...

42.0
42f
42e0

etc. Hope this helps.
Topic archived. No new replies allowed.