Accept all types as argument in function

前端 未结 5 1026
走了就别回头了
走了就别回头了 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:48

    You can use templates for this purpose:

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

    What you can actually do with the value may be rather limited without knowing its type -- it depends on the goal of your function. (If someone attempts to call the function with an argument type that causes that function specialization to be ill-formed then your template function will fail to instantiate and it will be a compile-time error.)

提交回复
热议问题