Take all types as an argument in a function

How can I in C ++ force a function to accept every object, so I can give it numbers, String or other objects. I'm not very good in C ++, hope this is not a completely stupid question ...

Edit: Okay, example: if you want to try to wrap std :: cout streams in regular functions, this funtion should be able to accept everything from integers over floating elements to complex objects. Hopefully this will become clearer now!

+4
source share
5 answers

You can overload your function for different types, i.e.

size_t func(int);
size_t func(std::string);

/ template, , ,

template<typename T>
size_t func(T const&) { return sizeof(T); }

, SFINAE, , T (.. , , , pod ..). func() ( ) , , , , . .

, , boost::any, ( )

size_t func(boost::any const&x)
{
  auto i = boost::any_cast<const int*>(x);
  if(i) return func(*i);
  // etc for other types, but this must be done at coding time!
}
+6

:

template <typename T>
void foo(T const & value)
{
    // value is of some type T, which can be any type at all.
}

, , , - . ( - , , , .)

+2

, , void .

void foo(void* bar);
+1

If I understood you correctly, you can try using the http://en.cppreference.com/w/cpp/language/function_template templates

+1
source

You are probably looking for patterns .
I suggest you read this .

0
source

All Articles