why didn't the positive terms get displayed in this asbolute program

前端 未结 4 828
鱼传尺愫
鱼传尺愫 2021-01-14 18:20

Let\'s start with this demo

#include 
using namespace std;

template 
void abs(T number)
{
   if (number < 0)
        numbe         


        
4条回答
  •  孤独总比滥情好
    2021-01-14 18:52

    There is an abs function built-in to the standard library:

    int abs ( int n );
    long abs ( long n );
    

    The compiler is going to use these versions in preference to your templated function since non-templated functions are more specific than templated functions, and thus take precedence in function overload resolution.

    I recommend that you rename your abs function to something else to fix this.

    As a side note, this might be questionable behavior on the part of your standard library implementation. It appears that #include is pulling in a non-std-namespaced declaration of abs and it probably shouldn't be doing that. If you switch to C-style printfs then your program works fine without having to rename anything (at least on my platform, that is).

    #include 
    
    template 
    void abs(T number)
    {
       if (number < 0)
            number = -number;
       printf("The absolute value of the number is %g\n", (double) number);
       return;
    }
    
    int main()
    {
       int num1 = 1;
       int num2 = 2;
       double num3 = -2.1333;
       float num4 = -4.23f;
    
       abs(num1);
       abs(num2);
       abs(num3);
       abs(num4);
    
       return 0;
    }
    

    I don't recommend that as a solution, just as a curiosity.

提交回复
热议问题