Accept all types as argument in function

前端 未结 5 1018
走了就别回头了
走了就别回头了 2020-12-15 09:41

How can I in C++ make a function accept every Object, so I can give it numbers, String or other Objects. I am not very well in C++, I hope it\'s not a totally stupid questio

5条回答
  •  伪装坚强ぢ
    2020-12-15 09:45

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

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

    Alternatively and/or additionally, you can provide a function template, which is a way to tell the compiler how to generate your function for any particular type, for example

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

    You may use more advanced techniques such as SFINAE to effectively overload those template functions, i.e. to use different templates for different kind of types T (i.e. integral types, pointer, built-in types, pod, etc). The compiler will then pick the best-fitting func() (if any) for any function call it encounters and, if this is a template, generate an appropriate function. This requires no re-coding.

    A completely different approach is to use a generic erasure type, such as boost::any, when the function will need to resolve the expected types at coding-time (as opposed to compile-time):

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

提交回复
热议问题