Why was function overloading added to C++?

前端 未结 6 1893
囚心锁ツ
囚心锁ツ 2021-02-03 21:03

I have a C background. I was just wondering why was function overloading added to C++? C doesn\'t have function overloading but C++ does, what was the need for it?

What

6条回答
  •  猫巷女王i
    2021-02-03 21:24

    One good reason, in addition to what DeadMG said, is that if you're writing a template function which e.g. calls sqrt, then you need a generic way of calling sqrt -- it would be very difficult if you had to try and somehow vary the name to sqrtf, sqrtd, etc., depending on the type of the template parameter. Overloading solves this problem, because then you just write sqrt and let the compiler figure out which overload it should be using:

    template 
    T sqrt_plus_one(T t) // contrived example
    {
      return sqrt(t) + 1;
    }
    

提交回复
热议问题