c++ - Accept all types as argument in function -


How can I accept a function in C ++ every object, so I give it a number, string, or other object Can i I'm not very well in C ++, I hope this is not a completely stupid question ...

EDIT: OK, example: if you have std :: Want to try wrapping the cout stream, that funtion should be able to accept everything - more floats than intangibles for complex objects. I hope this is more clear now!

You can overload to separate your work type, I.e.

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

Alternatively and / or additionally, you can provide a function template , which will allow the compiler to generate your function for a particular type of The example tells the example

  template & lt; Typename T & gt; Size_t func (T const & amp;) {return sizeof (t); }  

You can use more advanced techniques such as SFINE to effectively overload those template tasks, that is, for different types of types, different types of T < / Code> (i.e. integral type, indicator, built-up type, pod, etc.). After this, the compiler chooses the best-suitable func () (if any) for any function call, and if it is a template, then generate a suitable function. This does not require coding again.

A completely different approach is to use a normal deletion type , such as boost :: any , when the function coding requires the expected types of time Will need to be solved (contrary to compile time):

  size_t func (boost: any const & x) {auto i = boost :: any_cast & lt; Const int * & gt; (X); If (i) fenc (* i) returns; // etc for other types, but it should be done on time coding! }  

Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -